<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <!-- hexo-inject:begin --><!-- hexo-inject:end --><meta charset="utf-8">
    <meta name="keywords" content="javaScript, HTML,CSS,JavaScript,JQuery,React,Vue.js等">
    <meta name="description" content="别做一个Vue api调用师">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>javaScript | zihao blog</title>
    <link rel="icon" type="image/png" href="/pride-blog/favicon.png">

    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/pride-blog/css/my.css">

    <script src="/pride-blog/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.3.0"><link rel="stylesheet" href="/pride-blog/css/prism-tomorrow.css" type="text/css"><!-- hexo-inject:begin --><!-- hexo-inject:end --></head>




<body>
    <!-- hexo-inject:begin --><!-- hexo-inject:end --><header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/pride-blog/" class="waves-effect waves-light">
                    
                    <img src="/pride-blog/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">zihao blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/categories/CSS/" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/pride-blog/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/pride-blog/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">zihao blog</div>
        <div class="logo-desc">
            
            别做一个Vue api调用师
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/categories/CSS/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/pride-blog/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/pride-blog/medias/featureimages/3.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">javaScript</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/pride-blog/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        padding: 35px 0 15px 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        padding-bottom: 30px;
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/pride-blog/tags/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/">
                                <span class="chip bg-color">每天一个离职小技巧</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/pride-blog/categories/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/" class="post-category">
                                每天一个离职小技巧
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-08-04
                </div>
                

                

                

                

                
            </div>
        </div>
        <hr class="clearfix">

        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <h4 id="1-Window-onLoad-和-DOMContentLoaded事件的先后顺序"><a href="#1-Window-onLoad-和-DOMContentLoaded事件的先后顺序" class="headerlink" title="1.Window.onLoad 和 DOMContentLoaded事件的先后顺序?"></a>1.<code>Window.onLoad</code> 和 <code>DOMContentLoaded</code>事件的先后顺序?</h4><h4 id="顺序"><a href="#顺序" class="headerlink" title="顺序"></a>顺序</h4><p>一般情况下，<code>DOMContentLoaded</code>事件要在<code>window.onload</code>之前执行，当DOM树构建完成的时候就会执行 <code>DOMContentLoaded</code>事件，而<code>window.onload</code>是在页面载入完成的时候，才执行</p>
<h4 id="区别"><a href="#区别" class="headerlink" title="区别"></a>区别</h4><p>1、当 <code>onload</code> 事件触发时，页面上所有的<code>DOM</code>，样式表，脚本，图片，<code>flash</code>都已经加载完成了。</p>
<p>2、当 <code>DOMContentLoaded</code> 事件触发时，仅当<code>DOM</code>加载完成，不包括样式表，图片，<code>flash</code>。</p>
<h4 id="2-怎么实现this对象的深拷⻉"><a href="#2-怎么实现this对象的深拷⻉" class="headerlink" title="2.怎么实现this对象的深拷⻉?"></a>2.怎么实现<code>this</code>对象的深拷⻉?</h4><h4 id="1-一行代码的深拷贝"><a href="#1-一行代码的深拷贝" class="headerlink" title="1)一行代码的深拷贝"></a>1)一行代码的深拷贝</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">//创建mock数据</span>
<span class="token keyword">function</span> <span class="token function">createData</span><span class="token punctuation">(</span>deep<span class="token punctuation">,</span> breadth<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> data <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> temp <span class="token operator">=</span> data<span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> deep<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        temp <span class="token operator">=</span> temp<span class="token punctuation">[</span><span class="token string">'data'</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> j <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> j <span class="token operator">&lt;</span> breadth<span class="token punctuation">;</span> j<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
            temp<span class="token punctuation">[</span>j<span class="token punctuation">]</span> <span class="token operator">=</span> j<span class="token punctuation">;</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> data<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token function">createData</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token comment" spellcheck="true">// 1层深度，每层有3个数据 &amp;#123;data: &amp;#123;0: 0, 1: 1, 2: 2&amp;#125;&amp;#125;</span></code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">//深拷贝对象</span>
<span class="token keyword">function</span> <span class="token function">cloneJSON</span><span class="token punctuation">(</span>source<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> JSON<span class="token punctuation">.</span><span class="token function">parse</span><span class="token punctuation">(</span>JSON<span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>source<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>其实我第一次简单这个方法的时候，由衷的表示佩服，其实利用工具，达到目的，是非常聪明的做法</p>
<p>下面来测试下cloneJSON有没有溢出的问题，看起来cloneJSON内部也是使用递归的方式</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token function">cloneJSON</span><span class="token punctuation">(</span><span class="token function">createData</span><span class="token punctuation">(</span><span class="token number">10000</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span> 
<span class="token comment" spellcheck="true">//出现错误</span>
<span class="token comment" spellcheck="true">// Maximum call stack size exceeded</span></code></pre>
<p>既然是用了递归，那循环引用呢？并没有因为死循环而导致栈溢出啊，原来是JSON.stringify内部做了循环引用的检测，正是我们上面提到破解循环引用的第一种方法：循环检测</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> a <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
a<span class="token punctuation">.</span>a <span class="token operator">=</span> a<span class="token punctuation">;</span>

<span class="token function">cloneJSON</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> 
<span class="token comment" spellcheck="true">//出现错误</span>
<span class="token comment" spellcheck="true">// Uncaught TypeError: Converting circular structure to JSON</span></code></pre>
<h4 id="普通简单版本"><a href="#普通简单版本" class="headerlink" title="普通简单版本"></a>普通简单版本</h4><p>深拷贝的问题其实可以分解成两个问题，浅拷贝+递归，什么意思呢？假设我们有如下数据</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> a1 <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>b<span class="token punctuation">:</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>c<span class="token punctuation">:</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>d<span class="token punctuation">:</span> <span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span></code></pre>
<p>只需稍加改动上面浅拷贝的代码即可，注意区别</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">clone</span><span class="token punctuation">(</span>source<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> target <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token keyword">in</span> source<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>source<span class="token punctuation">.</span><span class="token function">hasOwnProperty</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
            <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> source<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">===</span> <span class="token string">'object'</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
                target<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token function">clone</span><span class="token punctuation">(</span>source<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// 注意这里</span>
            <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
                target<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> source<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">;</span>
            <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> target<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>其实上面的代码问题太多了，先来举几个例子吧</p>
<ul>
<li>没有对参数做检验</li>
<li>判断是否对象的逻辑不够严谨</li>
<li>没有考虑数组的兼容</li>
</ul>
<h4 id="进阶版本"><a href="#进阶版本" class="headerlink" title="进阶版本"></a>进阶版本</h4><p>用循环遍历一棵树，需要借助一个栈，当栈为空时就遍历完了，栈里面存储下一个需要拷贝的节点</p>
<p>首先我们往栈里放入种子数据，key用来存储放哪一个父元素的那一个子元素拷贝对象</p>
<p>然后遍历当前节点下的子元素，如果是对象就放到栈里，否则直接拷贝</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">cloneLoop</span><span class="token punctuation">(</span>x<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> root <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">// 栈</span>
  <span class="token keyword">const</span> loopList <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    parent<span class="token punctuation">:</span> root<span class="token punctuation">,</span>
    key<span class="token punctuation">:</span> undefined<span class="token punctuation">,</span>
    data<span class="token punctuation">:</span> x<span class="token punctuation">,</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">]</span>
  <span class="token keyword">while</span> <span class="token punctuation">(</span>loopList<span class="token punctuation">.</span>length<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">// 深度优先</span>
    <span class="token keyword">const</span> node <span class="token operator">=</span> loopList<span class="token punctuation">.</span><span class="token function">pop</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> parent <span class="token operator">=</span> node<span class="token punctuation">.</span>parent<span class="token punctuation">;</span>
    <span class="token keyword">const</span> key <span class="token operator">=</span> node<span class="token punctuation">.</span>key<span class="token punctuation">;</span>
    <span class="token keyword">const</span> data <span class="token operator">=</span> node<span class="token punctuation">.</span>data<span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">// 初始化赋值目标，key为undefined则拷贝到父元素，否则拷贝到子元素</span>
    <span class="token keyword">let</span> res <span class="token operator">=</span> parent<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> key <span class="token operator">!==</span> <span class="token string">"undefined"</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      res <span class="token operator">=</span> parent<span class="token punctuation">[</span>key<span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> k <span class="token keyword">in</span> data<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>data<span class="token punctuation">.</span><span class="token function">hasOwnProperty</span><span class="token punctuation">(</span>k<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> data<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">===</span> <span class="token string">"object"</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
          <span class="token comment" spellcheck="true">// 下一次循环</span>
          loopList<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
            parent<span class="token punctuation">:</span> res<span class="token punctuation">,</span>
            key<span class="token punctuation">:</span> k<span class="token punctuation">,</span>
            data<span class="token punctuation">:</span> data<span class="token punctuation">[</span>k<span class="token punctuation">]</span><span class="token punctuation">,</span>
          <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
          res<span class="token punctuation">[</span>k<span class="token punctuation">]</span> <span class="token operator">=</span> data<span class="token punctuation">[</span>k<span class="token punctuation">]</span><span class="token punctuation">;</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
      <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> root<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
</code></pre>
<h4 id="3-var-let-const-的区别，以及变量提升，函数提升"><a href="#3-var-let-const-的区别，以及变量提升，函数提升" class="headerlink" title="3.var let const 的区别，以及变量提升，函数提升?"></a>3.<code>var</code> <code>let</code> <code>const</code> 的区别，以及变量提升，函数提升?</h4><h4 id="var"><a href="#var" class="headerlink" title="var"></a>var</h4><p>1.不存在块作用域</p>
<p>2.可以多次声明（覆盖）</p>
<p>3.存在变量提升：当<code>var a = 1</code>;时候，会先在作用域的最顶端，<code>var a</code>;然后在<code>var a = 1</code>;的位置给a赋值</p>
<h4 id="let-const"><a href="#let-const" class="headerlink" title="let const"></a>let const</h4><p>1.存在块作用域</p>
<h3 id="经典例题："><a href="#经典例题：" class="headerlink" title="经典例题："></a>经典例题：</h3><p><code>for</code>循环给多个<code>dom</code>添加时间，输出<code>for</code>循环的角标i,如果用var声明，因为没有块作用域，<code>var</code>会变量提升到外层作用域最顶端，而多次i赋值，最后只保存了最后一次的值，改成let可以解决这个问题（这就是强行解释，具体为什么<code>let</code>可以解决还需要好好看看<code>let</code>)</p>
<p>2.不可以多次声明</p>
<p>包括<code>function a() &#123;&#125;</code>;存在后不能<code>let const a</code><br>变量提升和函数提升排序的问题需要理解</p>
<h4 id="4-node服务器优缺点"><a href="#4-node服务器优缺点" class="headerlink" title="4.node服务器优缺点?"></a>4.<code>node</code>服务器优缺点?</h4><p>1.优点：事件驱动，是的输入输出性能很高</p>
<p>2.缺点：<code>cpu</code>计算差，比如做很多计算操作，代码运行效率要求高，所以用底层的语言来做，比如<code>C</code></p>
<p>3.<code>io</code>密集型：需要处理比较多的任务</p>
<h4 id="5-WebSocket和socket的区别"><a href="#5-WebSocket和socket的区别" class="headerlink" title="5.WebSocket和socket的区别?"></a>5.<code>WebSocket</code>和<code>socket</code>的区别?</h4><p>就像<code>Java</code>和<code>JavaScript</code>，并没有什么太大的关系，但又不能说完全没关系。可以这么说：</p>
<ul>
<li>命名方面，Socket是一个深入人心的概念，WebSocket借用了这一概念；</li>
<li>使用方面，完全两个东西。</li>
</ul>
<h4 id="Socket"><a href="#Socket" class="headerlink" title="Socket"></a>Socket</h4><p>Socket可以有很多意思，和IT较相关的本意大致是指在端到端的一个连接中，这两个端叫做Socket。对于IT从业者来说，它往往指的是TCP/IP网络环境中的两个连接端，大多数的API提供者（如操作系统，JDK）往往会提供基于这种概念的接口，所以对于开发者来说也往往是在说一种编程概念。同时，操作系统中进程间通信也有Socket的概念，但这个Socket就不是基于网络传输层的协议了</p>
<h3 id="WebSocket与HTTP的关系"><a href="#WebSocket与HTTP的关系" class="headerlink" title="WebSocket与HTTP的关系"></a>WebSocket与HTTP的关系</h3><p><img src="https://img-blog.csdn.net/20170626140009906?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvU0xfaWRlYXM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast"></p>
<h4 id="相同点"><a href="#相同点" class="headerlink" title="相同点"></a>相同点</h4><p>都是一样基于<code>TCP</code>的，都是可靠性传输协议。</p>
<p>都是应用层协议。</p>
<h4 id="不同点"><a href="#不同点" class="headerlink" title="不同点"></a>不同点</h4><p><code>WebSocket</code>是双向通信协议，模拟<code>Socket</code>协议，可以双向发送或接受信息。HTTP是单向的。</p>
<p><code>WebSocket</code>是需要浏览器和服务器握手进行建立连接的。而<code>http</code>是浏览器发起向服务器的连接，服务器预先并不知道这个连接。</p>
<h4 id="联系"><a href="#联系" class="headerlink" title="联系"></a>联系</h4><p><code>WebSocket</code>在建立握手时，数据是通过<code>HTTP</code>传输的。但是建立之后，在真正传输时候是不需要<code>HTTP</code>协议的。</p>
<h3 id="总结："><a href="#总结：" class="headerlink" title="总结："></a>总结：</h3><p>在<code>WebSocket</code>中，只需要服务器和浏览器通过<code>HTTP</code>协议进行一个握手的动作，然后单独建立一条<code>TCP</code>的通信通道进行数据的传送。<br><code>WebSocket</code>连接的过程是：</p>
<p>首先，客户端发起<code>http</code>请求，经过3次握手后，建立起TCP连接；http请求里存放<code>WebSocket</code>支持的版本号等信息，如：<code>Upgrade</code>、<code>Connection</code>、<code>WebSocket-Version</code>等；</p>
<p>然后，服务器收到客户端的握手请求后，同样采用<code>HTTP</code>协议回馈数据；</p>
<p>最后，客户端收到连接成功的消息后，开始借助于<code>TCP</code>传输信道进行全双工通信</p>
<h4 id="6-ES6新的数组去重方法"><a href="#6-ES6新的数组去重方法" class="headerlink" title="6.ES6新的数组去重方法?"></a>6.<code>ES6</code>新的数组去重方法?</h4><p><code>es6</code>里新添加了两个很好用的东西，<code>set</code>和<code>Array.from</code>。</p>
<p><code>set</code>是一种新的数据结构，它可以接收一个数组或者是类数组对象，自动去重其中的重复项目。</p>
<p><code>set</code>返回的是一个对象，可以通过<code>Array.from</code>来转化为数组。</p>
<h4 id="7-不用for循环的情况下，打印出500个星号"><a href="#7-不用for循环的情况下，打印出500个星号" class="headerlink" title="7.不用for循环的情况下，打印出500个星号?"></a>7.不用<code>for</code>循环的情况下，打印出500个星号?</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">let</span> num <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> 
<span class="token keyword">while</span> <span class="token punctuation">(</span>num<span class="token operator">&lt;</span><span class="token number">500</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>   
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">"*"</span><span class="token punctuation">)</span>   
  num<span class="token operator">++</span><span class="token punctuation">;</span> 
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h4 id="8-storage和cookie的区别"><a href="#8-storage和cookie的区别" class="headerlink" title="8.storage和cookie的区别?"></a>8.<code>storage</code>和<code>cookie</code>的区别?</h4><p><code>Web Storage</code>的概念和<code>cookie</code>相似，区别是它是为了更大容量存储设计的。</p>
<p><code>Cookie</code>的大小是受限的，并且每次你请求一个新的页面的时候<code>Cookie</code>都会被发送过去，这样无形中浪费了带宽，另外<code>cookie</code>还需要指定作用域，不可以跨域调用。</p>
<p>除此之外，<code>Web Storage</code>拥有<code>setItem</code>,<code>getItem</code>,<code>removeItem</code>,<code>clear</code>等方法，不像<code>cookie</code>需要前端开发者自己封装<code>setCookie</code>，<code>getCookie</code>。</p>
<h3 id="但是Cookie也是不可以或缺的："><a href="#但是Cookie也是不可以或缺的：" class="headerlink" title="但是Cookie也是不可以或缺的："></a>但是<code>Cookie</code>也是不可以或缺的：</h3><p><code>Cookie</code>的作用是与服务器进行交互，作为<code>HTTP</code>规范的一部分而存在 ，而<code>Web Storage</code>仅仅是为了在本地“存储”数据而生</p>
<p>浏览器的支持除了<code>IE7</code>及以下不支持外，其他标准浏览器都完全支持(ie及FF需在web服务器里运行)，值得一提的是IE总是办好事，例如<code>IE7</code>、<code>IE6</code>中的<code>UserData</code>其实就是javascript本地存储的解决方案。通过简单的代码封装可以统一到所有的浏览器都支持<code>web storage</code>。</p>
<p><code>localStorage</code>和<code>sessionStorage</code>都具有相同的操作方法，例如<code>setItem</code>、<code>getItem</code>和<code>removeItem</code>等</p>
<h4 id="9-介绍js有哪些内置对象？"><a href="#9-介绍js有哪些内置对象？" class="headerlink" title="9.介绍js有哪些内置对象？"></a>9.介绍<code>js</code>有哪些内置对象？</h4><p><code>Object</code> 是 <code>JavaScript</code> 中所有对象的父对象  </p>
<p>数据封装类对象：<code>Object</code>、<code>Array</code>、<code>Boolean</code>、Number<code>和</code>String`    </p>
<p>其他对象：<code>Function</code>、<code>Arguments</code>、<code>Math</code>、<code>Date</code>、<code>RegEx</code>、<code>Error</code></p>
<h4 id="10-如何区分数组和对象？"><a href="#10-如何区分数组和对象？" class="headerlink" title="10.如何区分数组和对象？"></a>10.如何区分数组和对象？</h4><h4 id="方法1"><a href="#方法1" class="headerlink" title="方法1"></a>方法1</h4><p>通过Object,prototype.toString.call方法来识别</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> obj<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> array<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token number">1</span><span class="token punctuation">.</span>Object<span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>toString<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token string">"[Object Object]"</span>
<span class="token number">2</span><span class="token punctuation">.</span>Object<span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>toString<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>array<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token string">"[Object Array]"</span></code></pre>
<h4 id="方法2"><a href="#方法2" class="headerlink" title="方法2"></a>方法2</h4><p>通过ES6中的Array.isArray来识别</p>
<pre class=" language-javascript"><code class="language-javascript">Array<span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true">//true</span>
Array<span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span>  <span class="token comment" spellcheck="true">//false</span></code></pre>
<h4 id="方法3"><a href="#方法3" class="headerlink" title="方法3"></a>方法3</h4><p>通过intanceof</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> o<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> a<span class="token operator">=</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
o <span class="token keyword">instanceof</span> <span class="token class-name">Array</span> <span class="token comment" spellcheck="true">// false</span>
a <span class="token keyword">instanceof</span> <span class="token class-name">Array</span> <span class="token comment" spellcheck="true">// true</span></code></pre>
<h4 id="11-什么是闭包？"><a href="#11-什么是闭包？" class="headerlink" title="11.什么是闭包？"></a>11.什么是闭包？</h4><p>闭包是指有权访问另外一个函数作用域中的变量的函数。可以理解为(能够读取另一个函数作用域的变量的函数)</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">outer</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a <span class="token operator">=</span> <span class="token string">'变量1'</span>
    <span class="token keyword">var</span> inner <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
       console<span class="token punctuation">.</span><span class="token function">info</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
   <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
   <span class="token keyword">return</span> inner 
 <span class="token comment" spellcheck="true">// inner 就是一个闭包函数，因为他能够访问到outer函数的作用域</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>很多人会搞不懂匿名函数与闭包的关系，实际上，闭包是站在作用域的角度上来定义的。</p>
<p>因为<code>inner</code>访问到<code>outer</code>作用域的变量，所以<code>inner</code>就是一个闭包函数。</p>
<p>虽然定义很简单，但是有很多坑点，比如<code>this</code>指向、变量的作用域，稍微不注意可能就造成内存泄露。</p>
<h4 id="12-说说几个闭包的使用场景"><a href="#12-说说几个闭包的使用场景" class="headerlink" title="12.说说几个闭包的使用场景?"></a>12.说说几个闭包的使用场景?</h4><p>1.很多js流行框架都是使用匿名自执行函数来避免变量污染</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token punctuation">;</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">//todo</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>2.缓存:闭包可以让变量的值始终保存在内存中，因此在使用时也要注意不要滥用闭包</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">f1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> n<span class="token operator">=</span><span class="token number">999</span><span class="token punctuation">;</span>
    nAdd <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token operator">+</span><span class="token operator">=</span><span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">function</span> <span class="token function">f2</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token function">alert</span><span class="token punctuation">(</span>n<span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> f2<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> result <span class="token operator">=</span> <span class="token function">f1</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//注意只有f1的返回值被外部引用，才不会被回收</span>
<span class="token function">result</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// 999</span>
<span class="token function">nAdd</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">result</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">//1000</span></code></pre>
<p>3.封装</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> person <span class="token operator">=</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> name <span class="token operator">=</span> ‘<span class="token keyword">default</span>’
    <span class="token keyword">return</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        getName<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> <span class="token keyword">return</span> name<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span>
        setName<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span>newName<span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> name<span class="token operator">=</span>newName<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<h4 id="13-let-const-var-比较说明下？"><a href="#13-let-const-var-比较说明下？" class="headerlink" title="13.let const var 比较说明下？"></a>13.<code>let</code> <code>const</code> <code>var</code> 比较说明下？</h4><h3 id="理解js作用域"><a href="#理解js作用域" class="headerlink" title="理解js作用域"></a>理解js作用域</h3><p>在ES5中，js只有两种形式的作用域:全局作用域和函数作用域。</p>
<p>全局作用域：变量在程序中任意地方都可以访问到</p>
<p>函数作用域：变量在函数内部可以访问到，在函数外部无法访问</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">var</span> i<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a<span class="token operator">=</span><span class="token string">'a'</span>
    <span class="token keyword">let</span> b <span class="token operator">=</span> <span class="token string">'b'</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">//'a'</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">//'b' is not defined</span></code></pre>
<p>上述代码中，变量a为全局变量</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a <span class="token operator">=</span> <span class="token string">'a'</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
 <span class="token comment" spellcheck="true">// 函数外部无法直接访问函数内部变量，报错</span></code></pre>
<p>上述代码中，变量a为局部变量，控制台打印报错信息a is not defined</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    a <span class="token operator">=</span> <span class="token string">'a'</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token function">test</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">//'a'</span></code></pre>
<p>函数内部未使用var关键字定义变量，此时a为全局变量</p>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>ES5中, js的作用域分为全局作用域和函数作用域</p>
<p>函数内部可以访问函数外部的全局变量，函数外部却无法直接访问函数内部的局部变量</p>
<p>未使用var关键字定义的变量是全局变量</p>
<p>现在我们知道函数内部可以访问函数外部的全局变量，函数外部却无法直接访问函数内部的局部变量</p>
<h3 id="js中的变量提升"><a href="#js中的变量提升" class="headerlink" title="js中的变量提升"></a>js中的变量提升</h3><p>var定义变量存在变量提升：只提升声明语句，不提升赋值语句</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span>
    foo<span class="token punctuation">.</span>n <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">2</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span> </code></pre>
<p>执行上述代码，我们可以看到控制台中按顺序依次打印：1，2，3。这是因为Javascript先编译后执行。编译阶段，先声明变量，所以引擎会将上面的代码理解为以下格式</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> foo<span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span>
    foo<span class="token punctuation">.</span>n <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
    foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">2</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span></code></pre>
<h3 id="说明："><a href="#说明：" class="headerlink" title="说明："></a>说明：</h3><p>1.函数内部定义变量foo时，因为当前作用域中已经存在名为foo的变量，所以编译器忽略当前声明，继续进行编译，因此第一次打印的内容为外部变量foo的属性n值：1</p>
<p>2.foo.n=3 改变的是外部变量foo,foo={n:2}将foo指向了内部变量，并重新赋值为{n:2},所以第二次打印的内容为内部重新赋值的变量foo的属性n值：2</p>
<p>3.第三次打印内容是外部变量foo.n,因为函数内容已经更改了外部变量foo，所以打印结果为：3</p>
<p>js中先提升函数，后提升变量。</p>
<p>思考以下代码：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
    <span class="token keyword">var</span> a <span class="token operator">=</span><span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">function</span> <span class="token function">a</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>执行上述代码，我们可以看到控制台中按顺序依次打印：a(){},1。按照刚才的理解，js引擎将上面的代码会理解为下面的格式</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a<span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
    a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
    <span class="token keyword">function</span> <span class="token function">a</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>那打印的结果应该为 undefined ， f(){}，这是因为我们忽略了一点，js先提升函数，后提升变量。所以正确的格式为</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">function</span> <span class="token function">a</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a<span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
    a <span class="token operator">=</span> <span class="token number">1</span><span class="token punctuation">;</span>
   console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span></code></pre>
<p>说明：<br>1.定义变量a时，因为已经存在命名为a的函数，所以第一次打印结果为a(){}<br>2.a=1,将变量a重新赋值，所以第二次打印结果为1</p>
<h3 id="小结-1"><a href="#小结-1" class="headerlink" title="小结"></a>小结</h3><p>ES5中，使用var定义变量，变量的作用域有两种：全局作用域、函数作用域<br>var定义变量存在变量提升，此外，先提升函数，后提升变量<br>但是开发过程中，变量提升往往会对开发造成困扰，幸好ES6中引入了let语法。</p>
<h3 id="let"><a href="#let" class="headerlink" title="let"></a>let</h3><h4 id="块级作用域"><a href="#块级作用域" class="headerlink" title="块级作用域"></a>块级作用域</h4><p>我们刚才提到，ES5中，js只用两种作用域：全局作用域与函数作用域。在ES6中，let关键字会隐式地创建一个块级作用域（通常是{}内部），变量只能在这个作用域中被访问。例如题目一中</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">var</span> i<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">10</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a<span class="token operator">=</span><span class="token string">'a'</span>
    <span class="token keyword">let</span> b <span class="token operator">=</span> ‘b'
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>a<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>b<span class="token punctuation">)</span></code></pre>
<p>我们在循环的内部，使用let创建了变量b，在循环外部访问时报错，b is not defined.就是这个原因。<br>块级作用域的引入大大改善了代码中由于全局变量而引发的错误，比如文章开头提出的第二题：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">var</span> i<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">3</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span><span class="token number">1000</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>上述代码由于变量i是用var声明的，所以全局范围有效 ，当循环体执行完时，i=2,所以定时器中console.log(i)中的i是指向全局变量i的，所以打印结果为2，2，2<br>如果我们将代码改为</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span><span class="token punctuation">(</span><span class="token keyword">let</span> i<span class="token operator">=</span><span class="token number">0</span><span class="token punctuation">;</span>i<span class="token operator">&lt;</span><span class="token number">3</span><span class="token punctuation">;</span>i<span class="token operator">++</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span><span class="token number">1000</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>上述代码中，变量i使用let定义，所以只在本轮for循环中有效，所以打印结果为0，1，2。</p>
<p>let不存在变量提升，其所声明的变量一定要在声明语句之后使用。<br>例如：</p>
<pre><code>console.log(bar);
let bar = 2;</code></pre>
<p>打印结果报错：bar is not defined</p>
<p>此外，let 声明的变量不能重复声明，例如</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">let</span> foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
<span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span>
    foo<span class="token punctuation">.</span>n <span class="token operator">=</span> <span class="token number">3</span><span class="token punctuation">;</span>
    <span class="token keyword">let</span> foo <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>n<span class="token punctuation">:</span><span class="token number">2</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span>foo<span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>foo<span class="token punctuation">.</span>n<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>函数内部定义变量foo时，因为当前作用域中已经存在命名为foo的变量，所以报错：’foo’ has already been declared.</p>
<h3 id="const"><a href="#const" class="headerlink" title="const"></a>const</h3><p>ES6中新增了let关键字的同时，也新增了const关键字。<br>let与const有很多共同点：</p>
<ul>
<li>都支持块级作用域</li>
<li>都不支持变量提升</li>
<li>都不支持重复声明</li>
</ul>
<p>此外，我们知道var声明全局变量时，变量是挂在window上的。而let,const声明变量，却不是。这样子便避免了window对象的变量污染问题。</p>
<p><img src="https://yangyunhaiimagesoss.oss-cn-shanghai.aliyuncs.com/2009181704_1600419895474.png"></p>
<p>当然，const与let也有区别。const与let的区别在于：</p>
<p>let声明变量时无需赋值，const声明变量时必须赋值<br>let声明变量，变量可重新赋值，const声明变量，完成初始化后，值不得更改 （基本类型）</p>
<h4 id="14-下面输出的结果为"><a href="#14-下面输出的结果为" class="headerlink" title="14.下面输出的结果为?"></a>14.下面输出的结果为?</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// interviewer: what will the following code output?</span>
<span class="token keyword">const</span> arr <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token number">10</span><span class="token punctuation">,</span> <span class="token number">12</span><span class="token punctuation">,</span> <span class="token number">15</span><span class="token punctuation">,</span> <span class="token number">21</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
<span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'Index: '</span> <span class="token operator">+</span> i <span class="token operator">+</span> <span class="token string">', element: '</span> <span class="token operator">+</span> arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token number">3000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h3 id="解析："><a href="#解析：" class="headerlink" title="解析："></a>解析：</h3><pre><code>Index: 4, 
element: undefined（打印4次）</code></pre>
<p><code>setTimeout</code>函数创建了一个可以访问其外部作用域的函数（闭包），该外部作用域是包含index的循环i。延时3秒，被执行的功能和它打印出的值i，这在环路的端部是在4，因为它循环通过0，1，2，3，4和环路最终停止在第4 arr[4]做不存在，这就是为什么你得到undefined。</p>
<h4 id="15-以下代码将输出什么"><a href="#15-以下代码将输出什么" class="headerlink" title="15.以下代码将输出什么?"></a>15.以下代码将输出什么?</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">3</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> 
      console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">;</span> 
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>上面代码的目标是分别在1、1.1和1.2秒后提醒数字0、1和2。</p>
<p>但是，问题是，如果您在控制台中运行上述代码，则在1、1.1 和1.2秒后实际上会收到3次3号警报。</p>
<p>这是因为JavaScript闭包有问题。JavaScript 闭包是指内部函数可以访问其外部封装函数的变量和属性。在上面的代码中，以下代码行：</p>
<p>使用在自身外部声明的变量i。</p>
<p>实际上，变量i是在for循环中声明的，内部函数可以访问它。</p>
<p>因此，当for循环完成运行时，每个内部函数都引用相同的变量i，该变量在循环末尾等于3。</p>
<p>我们的目标是使每个内部函数在不使用变量i的情况下保持其对变量i的引用。它的价值正在改变。我们将使用IIFE或立即调用的函数表达式来解决此问题。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">var</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">3</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token function">setTimeout</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>i_local<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> 
    <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> 
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>i_local<span class="token punctuation">)</span><span class="token punctuation">;</span> 
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> 
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">(</span>i<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token number">1000</span> <span class="token operator">+</span> i<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>我们将变量i作为名为i_local的局部变量传递到外部函数中，然后在该函数中返回将向我们发出i_local警报的函数。现在，这应该以正确的顺序正确警告数字0、1和2。</p>
<h4 id="16-编写一个允许您执行此操作的函数"><a href="#16-编写一个允许您执行此操作的函数" class="headerlink" title="16.编写一个允许您执行此操作的函数!"></a>16.编写一个允许您执行此操作的函数!</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> addSix <span class="token operator">=</span> <span class="token function">createBase</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">addSix</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// returns 16</span>
<span class="token function">addSix</span><span class="token punctuation">(</span><span class="token number">21</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// returns 27</span></code></pre>
<p>解析：</p>
<p>您可以创建一个闭包，以保持将值传递给函数createBase，即使在返回内部函数之后也是如此。返回的内部函数是在外部函数内创建的，使其成为一个闭包，并且可以访问外部函数内的变量，在本例中为变量baseNumber。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">createBase</span><span class="token punctuation">(</span>baseNumber<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span>N<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> baseNumber <span class="token operator">+</span> N<span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> addSix <span class="token operator">=</span> <span class="token function">createBase</span><span class="token punctuation">(</span><span class="token number">6</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">addSix</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token function">addSix</span><span class="token punctuation">(</span><span class="token number">21</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<h4 id="17-让函数FirstReverse（str）接受传递的str参数，并以相反的顺序返回字符串。"><a href="#17-让函数FirstReverse（str）接受传递的str参数，并以相反的顺序返回字符串。" class="headerlink" title="17.让函数FirstReverse（str）接受传递的str参数，并以相反的顺序返回字符串。"></a>17.让函数<code>FirstReverse（str）</code>接受传递的str参数，并以相反的顺序返回字符串。</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">//输入：</span>
<span class="token function">FirstReverse</span><span class="token punctuation">(</span><span class="token string">"Hello World and Coders"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment" spellcheck="true">//输出</span>
sredoC dna dlroW olleH</code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">FirstReverse</span><span class="token punctuation">(</span>string<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> string<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">reverse</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token function">FirstReverse</span><span class="token punctuation">(</span><span class="token string">"Hello World and Coders"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
<p>标签:字符串操作</p>
<h5 id="18-使函数LongestWord（sen）接受传递的sen参数，并返回字符串中最大的单词。"><a href="#18-使函数LongestWord（sen）接受传递的sen参数，并返回字符串中最大的单词。" class="headerlink" title="18.使函数LongestWord（sen）接受传递的sen参数，并返回字符串中最大的单词。"></a>18.使函数<code>LongestWord（sen）</code>接受传递的sen参数，并返回字符串中最大的单词。</h5><p>如果有两个或更多个相同长度的单词，则从字符串中返回具有该长度的第一个单词。忽略标点符号，并假定sen不会为空。</p>
<pre class=" language-javascript"><code class="language-javascript">输入：“ fun＆<span class="token operator">!</span><span class="token operator">!</span> time”
输出：time
输入：“I love dogs”
输出：love</code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">LongestWord</span><span class="token punctuation">(</span>sen<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  sen <span class="token operator">=</span> sen<span class="token punctuation">.</span><span class="token function">trim</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  sen <span class="token operator">=</span> sen<span class="token punctuation">.</span><span class="token function">replace</span><span class="token punctuation">(</span><span class="token regex">/[^a-zA-Z0-9 ]/g</span><span class="token punctuation">,</span> <span class="token string">''</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> longest <span class="token operator">=</span> <span class="token string">""</span>
  <span class="token keyword">var</span> arr <span class="token operator">=</span> sen<span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">" "</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>word <span class="token operator">=</span><span class="token operator">></span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span><span class="token punctuation">(</span>word<span class="token punctuation">.</span>length <span class="token operator">></span> longest<span class="token punctuation">.</span>length<span class="token punctuation">)</span> longest <span class="token operator">=</span> word<span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span>
  <span class="token keyword">return</span> longest<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token function">LongestWord</span><span class="token punctuation">(</span><span class="token string">"fun＆!! time"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment" spellcheck="true">// 输出：time</span></code></pre>
<p>标签:最长字,字符串操作,查找</p>
<h4 id="19-让函数FindIntersection（strArr）读取存储在strArr中的字符串数组，该数组将包含2个元素："><a href="#19-让函数FindIntersection（strArr）读取存储在strArr中的字符串数组，该数组将包含2个元素：" class="headerlink" title="19.让函数FindIntersection（strArr）读取存储在strArr中的字符串数组，该数组将包含2个元素："></a>19.让函数<code>FindIntersection（strArr）</code>读取存储在strArr中的字符串数组，该数组将包含2个元素：</h4><p>第一个元素将代表以逗号分隔的数字列表，以升序排列，第二个元素将代表第二个以逗号分隔的列表数字（也排序）。</p>
<p>您的目标是返回一个逗号分隔的字符串，其中包含按排序顺序出现在strArr元素中的数字。如果没有交集，则返回字符串false。</p>
<pre class=" language-javaScript"><code class="language-javaScript">输入：["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"]
输出：1,4,13</code></pre>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> FindIntersection <span class="token punctuation">(</span>strArr<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">const</span> inBothStrings <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span>
  <span class="token keyword">const</span> arr1 <span class="token operator">=</span> strArr<span class="token punctuation">[</span><span class="token number">0</span><span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">', '</span><span class="token punctuation">)</span>
  <span class="token keyword">const</span> arr2 <span class="token operator">=</span> strArr<span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">', '</span><span class="token punctuation">)</span>
  arr1<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>elementArr1 <span class="token operator">=</span><span class="token operator">></span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">const</span> numArr1 <span class="token operator">=</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>elementArr1<span class="token punctuation">)</span>
    arr2<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span>elementArr2 <span class="token operator">=</span><span class="token operator">></span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      <span class="token keyword">const</span> numArr2 <span class="token operator">=</span> <span class="token function">parseInt</span><span class="token punctuation">(</span>elementArr2<span class="token punctuation">)</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>numArr1 <span class="token operator">===</span> numArr2<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        inBothStrings<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>numArr1<span class="token punctuation">)</span>
      <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span>
  <span class="token keyword">return</span> inBothStrings<span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">','</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token function">FindIntersection</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">"1, 3, 4, 7, 13"</span><span class="token punctuation">,</span> <span class="token string">"1, 2, 4, 13, 15"</span><span class="token punctuation">]</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// 输出："1,4,13"</span></code></pre>
<h5 id="20-有一个大数组"><a href="#20-有一个大数组" class="headerlink" title="20.有一个大数组:"></a>20.有一个大数组:</h5><pre><code>var a = [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, ...]</code></pre>
<p><code>a</code> 的长度是 <code>100</code>,内容填充随机整数的字符串.请先构造此数组 <code>a</code>,然后设计一个算法将其内容去重</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">/**
 * 数组去重
 **/</span>
 <span class="token keyword">function</span> <span class="token function">normalize</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
     <span class="token keyword">if</span> <span class="token punctuation">(</span>arr <span class="token operator">&amp;&amp;</span> Array<span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span>arr<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
         <span class="token keyword">var</span> i<span class="token punctuation">,</span> len<span class="token punctuation">,</span> map <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>
         <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> arr<span class="token punctuation">.</span>length<span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">0</span><span class="token punctuation">;</span> <span class="token operator">--</span>i<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
             <span class="token keyword">if</span> <span class="token punctuation">(</span>arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token keyword">in</span> map<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
                 arr<span class="token punctuation">.</span><span class="token function">splice</span><span class="token punctuation">(</span>i<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
             <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
                 map<span class="token punctuation">[</span>arr<span class="token punctuation">[</span>i<span class="token punctuation">]</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
             <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
         <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
     <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
     <span class="token keyword">return</span> arr<span class="token punctuation">;</span>
 <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

 <span class="token comment" spellcheck="true">/**
 * 用100个随机整数对应的字符串填充数组。
 **/</span>
 <span class="token keyword">function</span> <span class="token function">fillArray</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> start<span class="token punctuation">,</span> end<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
     start <span class="token operator">=</span> start <span class="token operator">==</span> undefined <span class="token operator">?</span> <span class="token number">1</span> <span class="token punctuation">:</span> start<span class="token punctuation">;</span>
     end <span class="token operator">=</span> end <span class="token operator">==</span> undefined <span class="token operator">?</span>  <span class="token number">100</span> <span class="token punctuation">:</span> end<span class="token punctuation">;</span>

     <span class="token keyword">if</span> <span class="token punctuation">(</span>end <span class="token operator">&lt;=</span> start<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
         end <span class="token operator">=</span> start <span class="token operator">+</span> <span class="token number">100</span><span class="token punctuation">;</span>
     <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

     <span class="token keyword">var</span> width <span class="token operator">=</span> end <span class="token operator">-</span> start<span class="token punctuation">;</span>
     <span class="token keyword">var</span> i<span class="token punctuation">;</span>
     <span class="token keyword">for</span> <span class="token punctuation">(</span>i <span class="token operator">=</span> <span class="token number">100</span><span class="token punctuation">;</span> i <span class="token operator">>=</span> <span class="token number">1</span><span class="token punctuation">;</span> <span class="token operator">--</span>i<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
         arr<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span><span class="token string">''</span> <span class="token operator">+</span> <span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">*</span> width<span class="token punctuation">)</span> <span class="token operator">+</span> start<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
     <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
     <span class="token keyword">return</span> arr<span class="token punctuation">;</span>
 <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

 <span class="token keyword">var</span> input <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
 <span class="token function">fillArray</span><span class="token punctuation">(</span>input<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">100</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 input<span class="token punctuation">.</span><span class="token function">sort</span><span class="token punctuation">(</span><span class="token keyword">function</span> <span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
     <span class="token keyword">return</span> a <span class="token operator">-</span> b<span class="token punctuation">;</span>
 <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
 console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span><span class="token punctuation">;</span>

 <span class="token function">normalize</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span><span class="token punctuation">;</span>
 console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>input<span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre>
<h5 id="21-JS延迟加载的方式有哪些？"><a href="#21-JS延迟加载的方式有哪些？" class="headerlink" title="21.JS延迟加载的方式有哪些？"></a>21.<code>JS</code>延迟加载的方式有哪些？</h5><p>1、 <code>JS</code>的延迟加载有助与提高页面的加载速度。</p>
<p>2、 <code>defer</code>和<code>async</code>、动态创建<code>DOM</code>方式（用得最多）、按需异步载入</p>
<p>3、 <code>JSdefer</code>：延迟脚本。立即下载，但延迟执行（延迟到整个页面都解析完毕后再运行），按照脚本出现的先后顺序执行。</p>
<p>4、 <code>async</code>：异步脚本。下载完立即执行，但不保证按照脚本出现的先后顺序执行。</p>
<h5 id="22-new操作符具体干了什么呢"><a href="#22-new操作符具体干了什么呢" class="headerlink" title="22.new操作符具体干了什么呢?"></a>22.<code>new</code>操作符具体干了什么呢?</h5><ol>
<li><p>创建一个空对象，并且 <code>this</code> 变量引用该对象，同时还继承了该函数的原型。</p>
</li>
<li><p>属性和方法被加入到 <code>this</code> 引用的对象中。</p>
</li>
<li><p>新创建的对象由 <code>this</code> 所引用，并且最后隐式的返回 <code>this</code> 。</p>
</li>
</ol>
<h5 id="23-quot-1-quot-quot-2-quot-quot-3-quot-map-parseInt-答案是多少？"><a href="#23-quot-1-quot-quot-2-quot-quot-3-quot-map-parseInt-答案是多少？" class="headerlink" title="23.[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;].map(parseInt) 答案是多少？"></a>23.<code>[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;].map(parseInt)</code> 答案是多少？</h5><h3 id="答案"><a href="#答案" class="headerlink" title="答案"></a>答案</h3><p><code>[1,NaN,NaN]</code></p>
<h3 id="解析：-1"><a href="#解析：-1" class="headerlink" title="解析："></a>解析：</h3><p>Array.prototype.map()<br>array.map(callback[, thisArg])<br>callback函数的执行规则参数：</p>
<p>自动传入三个参数：</p>
<ul>
<li>currentValue（当前被传递的元素）；</li>
<li>index（当前被传递的元素的索引）；</li>
<li>array（调用map方法的数组）</li>
</ul>
<p>parseInt方法接收两个参数：<br>第三个参数<code>[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]</code>将被忽略。</p>
<p><code>parseInt</code>方法将会通过以下方式被调用<br><code>parseInt(&quot;1&quot;, 0)</code></p>
<p><code>parseInt(&quot;2&quot;, 1)</code></p>
<p><code>parseInt(&quot;3&quot;, 2)</code></p>
<p>parseInt的第二个参数radix为0时，ECMAScript5将string作为十进制数字的字符串解析；</p>
<p>parseInt的第二个参数radix为1时，解析结果为NaN；</p>
<p>parseInt的第二个参数radix在2—36之间时，如果string参数的第一个字符（除空白以外），不属于radix指定进制下的字符，解析结果为NaN。</p>
<p>parseInt(“3”, 2)执行时，由于”3”不属于二进制字符，解析结果为NaN。</p>
<h5 id="24-谈谈this的理解"><a href="#24-谈谈this的理解" class="headerlink" title="24.谈谈this的理解"></a>24.谈谈<code>this</code>的理解</h5><p>  1、 <code>this</code>总是指向函数的直接调用者（而非间接调用者）</p>
<p>  2、 如果有<code>new</code>关键字，<code>this</code>指向<code>new</code>出来的那个对象</p>
<p>  3、在事件中，this指向目标元素，特殊的是IE的<code>attachEvent</code>中的<code>this</code>总是指向全局对象<code>window</code>。</p>
<h5 id="25-介绍JavaScript的基本数据类型"><a href="#25-介绍JavaScript的基本数据类型" class="headerlink" title="25.介绍JavaScript的基本数据类型"></a>25.介绍<code>JavaScript</code>的基本数据类型</h5><ul>
<li>Number</li>
<li>String</li>
<li>Boolean</li>
<li>Null</li>
<li>Undefined</li>
</ul>
<blockquote>
<p>Object 是 JavaScript 中所有对象的父对象</p>
</blockquote>
<h4 id="数据封装类对象："><a href="#数据封装类对象：" class="headerlink" title="数据封装类对象："></a>数据封装类对象：</h4><p><code>Object</code>、<code>Array</code>、<code>Boolean</code>、<code>Number</code> 和 <code>String</code></p>
<h4 id="其他对象："><a href="#其他对象：" class="headerlink" title="其他对象："></a>其他对象：</h4><p><code>Function</code>、<code>Arguments</code>、<code>Math</code>、<code>Date</code>、<code>RegExp</code>、<code>Error</code></p>
<h4 id="新类型："><a href="#新类型：" class="headerlink" title="新类型："></a>新类型：</h4><p><code>Symbol</code>、<code>BigInt</code></p>
<h5 id="26-什么是window对象-什么是document对象"><a href="#26-什么是window对象-什么是document对象" class="headerlink" title="26.什么是window对象? 什么是document对象?"></a>26.什么是<code>window</code>对象? 什么是<code>document</code>对象?</h5><p><code>window</code>对象代表浏览器中打开的一个窗口。</p>
<p><code>document</code>对象代表整个<code>html</code>文档。</p>
<p>实际上，<code>document</code>对象是<code>window</code>对象的一个属性。</p>
<h4 id="27-通过什什么做到并发请求"><a href="#27-通过什什么做到并发请求" class="headerlink" title="27.通过什什么做到并发请求?"></a>27.通过什什么做到并发请求?</h4><p>使用异步<code>Prmosie All</code>或者<code>web worker</code></p>
<h4 id="28-eval是做什么的？"><a href="#28-eval是做什么的？" class="headerlink" title="28.eval是做什么的？"></a>28.<code>eval</code>是做什么的？</h4><p>它的功能是把对应的字符串解析成<code>JS</code>代码并运行；</p>
<p>应该避免使用<code>eval</code>，不安全，非常耗性能（2次，一次解析成js语句，一次执行）。</p>
<h4 id="29-null，undefined的区别？"><a href="#29-null，undefined的区别？" class="headerlink" title="29.null，undefined的区别？"></a>29.<code>null</code>，<code>undefined</code>的区别？</h4><p><code>null</code>表示一个”无”的对象，也就是该处不应该有值；而<code>undefined</code>表示未定义。</p>
<p>在转换为数字时结果不同，<code>Number(null)</code>为0，而<code>undefined</code>为<code>NaN</code>。</p>
<blockquote>
<p>使用场景上：</p>
</blockquote>
<h3 id="null："><a href="#null：" class="headerlink" title="null："></a>null：</h3><p>作为函数的参数，表示该函数的参数不是对象<br>作为对象原型链的终点</p>
<h3 id="undefined"><a href="#undefined" class="headerlink" title="undefined:"></a>undefined:</h3><ol>
<li>变量被声明了，但没有赋值时，就等于undefined</li>
<li>调用函数时，应该提供的参数没有提供，该参数等于undefined</li>
<li>对象没有赋值属性，该属性的值为undefined</li>
<li>函数没有返回值时，默认返回undefined</li>
</ol>
<p><code>null</code>表示一个对象被定义了，但存放了空指针，转换为数值时为0。</p>
<p><code>undefined</code>表示声明的变量未初始化，转换为数值时为NAN。</p>
<p><code>typeof(null)</code> – object;</p>
<p><code>typeof(undefined)</code> – undefined</p>
<h4 id="30-解释-call-apply-原理，并手写-call-apply-实现"><a href="#30-解释-call-apply-原理，并手写-call-apply-实现" class="headerlink" title="30.解释 call/apply 原理，并手写 call/apply 实现"></a>30.解释 <code>call/apply</code> 原理，并手写 <code>call/apply</code> 实现</h4><p>Function.prototype.call() call() 方法调用一个函数, 其具有一个指定的 this 值和多个参数(参数的列表)。</p>
<p>func.call(thisArg, arg1, arg2, …) 它运行 func，提供的第一个参数 thisArg 作为this，后面的作为参数。</p>
<h3 id="看一个简单的例子："><a href="#看一个简单的例子：" class="headerlink" title="看一个简单的例子："></a>看一个简单的例子：</h3><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">sayWord</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">var</span> talk <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token keyword">this</span><span class="token punctuation">.</span>name<span class="token punctuation">,</span> <span class="token string">'say'</span><span class="token punctuation">,</span>                
  <span class="token keyword">this</span><span class="token punctuation">.</span>word<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">join</span><span class="token punctuation">(</span><span class="token string">' '</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>talk<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> bottle <span class="token operator">=</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  name<span class="token punctuation">:</span> <span class="token string">'bottle'</span><span class="token punctuation">,</span> 
  word<span class="token punctuation">:</span> <span class="token string">'hello'</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">//使用 call 将 bottle 传递为 sayWord 的 this</span>
sayWord<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>bottle<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment" spellcheck="true">//bottle say hello</span>
所以，call 主要实现了以下两个功能：

<span class="token comment" spellcheck="true">//call 改变了 this 的指向</span>
<span class="token comment" spellcheck="true">//bottle 执行了 sayWord 函数</span>
<span class="token comment" spellcheck="true">//模拟实现 call</span>
<span class="token comment" spellcheck="true">//模拟实现 call 有三步：</span>

<span class="token comment" spellcheck="true">//将函数设置为对象的属性</span>
<span class="token comment" spellcheck="true">//执行函数</span>
<span class="token comment" spellcheck="true">//删除对象的这个属性</span>
Function<span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>call <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>context<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">// 将函数设为对象的属性</span>
  <span class="token comment" spellcheck="true">// 注意：非严格模式下, </span>
  <span class="token comment" spellcheck="true">// 指定为 null 和 undefined 的 this 值会自动指向全局对象(浏览器中就是 window 对象)</span>
  <span class="token comment" spellcheck="true">// 值为原始值(数字，字符串，布尔值)的 this 会指向该原始值的自动包装对象(用 Object() 转换）</span>
  context <span class="token operator">=</span> context <span class="token operator">?</span> <span class="token function">Object</span><span class="token punctuation">(</span>context<span class="token punctuation">)</span> <span class="token punctuation">:</span> window<span class="token punctuation">;</span> 
  context<span class="token punctuation">.</span>fn <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

  <span class="token comment" spellcheck="true">// 执行该函数</span>
  <span class="token keyword">let</span> args <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token operator">...</span>arguments<span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">slice</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> result <span class="token operator">=</span> context<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>

  <span class="token comment" spellcheck="true">// 删除该函数</span>
  <span class="token keyword">delete</span> context<span class="token punctuation">.</span>fn
  <span class="token comment" spellcheck="true">// 注意：函数是可以有返回值的</span>
  <span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<p>Function.prototype.apply() apply() 方法调用一个具有给定 this值的函数，以及作为一个数组（或[类似数组对象）提供的参数。</p>
<p>func.apply(thisArg, [argsArray]) 它运行 func 设置 this = context 并使用类数组对象 args 作为参数列表。</p>
<p>例如，这两个调用几乎相同：</p>
<h3 id="func-1-2-3"><a href="#func-1-2-3" class="headerlink" title="func(1, 2, 3);"></a>func(1, 2, 3);</h3><p>func.apply(context, [1, 2, 3]) 两个都运行 func 给定的参数是 1,2,3。但是 apply 也设置了 this = context。</p>
<p>call 和 apply 之间唯一的语法区别是 call 接受一个参数列表，而 apply 则接受带有一个类数组对象。</p>
<p>需要注意：Chrome 14 以及 Internet Explorer 9 仍然不接受类数组对象。如果传入类数组对象，它们会抛出异常。</p>
<h3 id="模拟实现-apply"><a href="#模拟实现-apply" class="headerlink" title="模拟实现 apply"></a>模拟实现 apply</h3><pre class=" language-javascript"><code class="language-javascript">Function<span class="token punctuation">.</span>prototype<span class="token punctuation">.</span>apply <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>context<span class="token punctuation">,</span> arr<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    context <span class="token operator">=</span> context <span class="token operator">?</span> <span class="token function">Object</span><span class="token punctuation">(</span>context<span class="token punctuation">)</span> <span class="token punctuation">:</span> window<span class="token punctuation">;</span> 
    context<span class="token punctuation">.</span>fn <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

    <span class="token keyword">let</span> result<span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>arr<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        result <span class="token operator">=</span> context<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        result <span class="token operator">=</span> context<span class="token punctuation">.</span><span class="token function">fn</span><span class="token punctuation">(</span><span class="token operator">...</span>arr<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

    <span class="token keyword">delete</span> context<span class="token punctuation">.</span>fn
    <span class="token keyword">return</span> result<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h4 id="31-如何判断一个对象是否属于某个类？"><a href="#31-如何判断一个对象是否属于某个类？" class="headerlink" title="31.如何判断一个对象是否属于某个类？"></a>31.如何判断一个对象是否属于某个类？</h4><p>使用<code>instanceof</code> 即</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">if</span><span class="token punctuation">(</span>a <span class="token keyword">instanceof</span> <span class="token class-name">Person</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token function">alert</span><span class="token punctuation">(</span><span class="token string">'yes'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h4 id="32-同步和异步的区别"><a href="#32-同步和异步的区别" class="headerlink" title="32.#####  同步和异步的区别?"></a>32.#####  同步和异步的区别?</h4><h3 id="同步的概念在操作系统中："><a href="#同步的概念在操作系统中：" class="headerlink" title="同步的概念在操作系统中："></a>同步的概念在操作系统中：</h3><p>不同进程协同完成某项工作而先后次序调整（通过阻塞、唤醒等方式），同步强调的是顺序性，谁先谁后。异步不存在顺序性。</p>
<h4 id="同步："><a href="#同步：" class="headerlink" title="同步："></a>同步：</h4><p>浏览器访问服务器，用户看到页面刷新，重新发请求，等请求完，页面刷新，新内容出现，用户看到新内容之后进行下一步操作。</p>
<h4 id="异步："><a href="#异步：" class="headerlink" title="异步："></a>异步：</h4><p>浏览器访问服务器请求，用户正常操作，浏览器在后端进行请求。等请求完，页面不刷新，新内容也会出现，用户看到新内容。</p>
<h4 id="33-一秒理解HTTP-状态码及其含义"><a href="#33-一秒理解HTTP-状态码及其含义" class="headerlink" title="33.一秒理解HTTP 状态码及其含义"></a>33.一秒理解<code>HTTP</code> 状态码及其含义</h4><h3 id="1XX：信息状态码"><a href="#1XX：信息状态码" class="headerlink" title="1XX：信息状态码"></a>1XX：信息状态码</h3><p>100 Continue：客户端应当继续发送请求。这个临时相应是用来通知客户端它的部分请求已经被服务器接收，且仍未被拒绝。客户端应当继续发送请求的剩余部分，或者如果请求已经完成，忽略这个响应。服务器必须在请求完成后向客户端发送一个最终响应</p>
<p>101 Switching Protocols：服务器已经理解 le 客户端的请求，并将通过 Upgrade 消息头通知客户端采用不同的协议来完成这个请求。在发送完这个响应最后的空行后，服务器将会切换到 Upgrade 消息头中定义的那些协议。</p>
<h3 id="2XX：成功状态码"><a href="#2XX：成功状态码" class="headerlink" title="2XX：成功状态码"></a>2XX：成功状态码</h3><ul>
<li>200 OK：请求成功，请求所希望的响应头或数据体将随此响应返回</li>
<li>201 Created：</li>
<li>202 Accepted：</li>
<li>203 Non-Authoritative Information：</li>
<li>204 No Content：</li>
<li>205 Reset Content：</li>
<li>206 Partial Content：</li>
</ul>
<h3 id="3XX：重定向"><a href="#3XX：重定向" class="headerlink" title="3XX：重定向"></a>3XX：重定向</h3><ul>
<li>300 Multiple Choices：</li>
<li>301 Moved Permanently：</li>
<li>302 Found：</li>
<li>303 See Other：</li>
<li>304 Not Modified：</li>
<li>305 Use Proxy：</li>
<li>306 （unused）：</li>
<li>307 Temporary Redirect：</li>
</ul>
<h3 id="4XX：客户端错误"><a href="#4XX：客户端错误" class="headerlink" title="4XX：客户端错误"></a>4XX：客户端错误</h3><ul>
<li>400 Bad Request:</li>
<li>401 Unauthorized:</li>
<li>402 Payment Required:</li>
<li>403 Forbidden:</li>
<li>404 Not Found:</li>
<li>405 Method Not Allowed:</li>
<li>406 Not Acceptable:</li>
<li>407 Proxy Authentication Required:</li>
<li>408 Request Timeout:</li>
<li>409 Conflict:</li>
<li>410 Gone:</li>
<li>411 Length Required:</li>
<li>412 Precondition Failed:</li>
<li>413 Request Entity Too Large:</li>
<li>414 Request-URI Too Long:</li>
<li>415 Unsupported Media Type:</li>
<li>416 Requested Range Not Satisfiable:</li>
<li>417 Expectation Failed:</li>
</ul>
<h3 id="5XX-服务器错误"><a href="#5XX-服务器错误" class="headerlink" title="5XX: 服务器错误"></a>5XX: 服务器错误</h3><ul>
<li>500 Internal Server Error:</li>
<li>501 Not Implemented:</li>
<li>502 Bad Gateway:</li>
<li>503 Service Unavailable:</li>
<li>504 Gateway Timeout:</li>
<li>505 HTTP Version Not Supported:</li>
</ul>
<p>1、创建一个新对象，继承自<code>func.prototype</code></p>
<p>2、执行构造函数，<code>this</code>会指向新创建的对象</p>
<p>3、如果构造函数返回一个对象，则该对象便是<code>new</code>出来的结果，如果构造函数没有返回对象，那么<code>new</code>出来的结果为步骤1创建的对象。</p>
<h4 id="34-JS单例模式"><a href="#34-JS单例模式" class="headerlink" title="34.JS单例模式"></a>34.<code>JS</code>单例模式</h4><h3 id="闭包的写法："><a href="#闭包的写法：" class="headerlink" title="闭包的写法："></a>闭包的写法：</h3><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">class</span> <span class="token class-name">Singleton</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
Singleton<span class="token punctuation">.</span>getInstance <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> instance
  <span class="token keyword">return</span> <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>instance<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      instance <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Singleton</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> instance
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> s1 <span class="token operator">=</span> Singleton<span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token keyword">let</span> s2 <span class="token operator">=</span> Singleton<span class="token punctuation">.</span><span class="token function">getInstance</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>s1 <span class="token operator">===</span> s2<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// true</span></code></pre>
<h3 id="非闭包的写法："><a href="#非闭包的写法：" class="headerlink" title="非闭包的写法："></a>非闭包的写法：</h3><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">Universe</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">// 判断是否存在实例 </span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> Universe<span class="token punctuation">.</span>instance <span class="token operator">===</span> <span class="token string">'object'</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">return</span> Universe<span class="token punctuation">.</span>instance<span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

  <span class="token comment" spellcheck="true">// 其它内容 </span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>start_time <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token keyword">this</span><span class="token punctuation">.</span>bang <span class="token operator">=</span> <span class="token string">"Big"</span><span class="token punctuation">;</span>

  <span class="token comment" spellcheck="true">// 缓存 </span>
  Universe<span class="token punctuation">.</span>instance <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">;</span>

  <span class="token comment" spellcheck="true">// 隐式返回this </span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">// 测试 </span>
<span class="token keyword">var</span> uni <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Universe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">var</span> uni2 <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Universe</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>uni <span class="token operator">===</span> uni2<span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// true</span></code></pre>
<h5 id="35-JS垃圾回收机制？"><a href="#35-JS垃圾回收机制？" class="headerlink" title="35.JS垃圾回收机制？"></a>35.<code>JS</code>垃圾回收机制？</h5><h3 id="1、-标记清除："><a href="#1、-标记清除：" class="headerlink" title="1、 标记清除："></a>1、 标记清除：</h3><p>当变量进入执行环境时标记为“<code>进入环境</code>”，当变量离开执行环境时则标记为“<code>离开环境</code>”，被标记为“<code>进入环境</code>”的变量是不能被回收的，因为它们正在被使用，而标记为“<code>离开环境</code>”的变量则可以被回收</p>
<h3 id="2、-引用计数："><a href="#2、-引用计数：" class="headerlink" title="2、 引用计数："></a>2、 引用计数：</h3><p>统计引用类型变量声明后被引用的次数，当次数为 0 时，该变量将被回收。</p>
<p>但是引用计数的方式，有一个相对明显的缺点——循环引用</p>
<p>在现代浏览器中，<code>Javascript</code> 使用的方式是标记清除，所以我们无需担心循环引用的问题</p>
<h3 id="3、-内存泄露"><a href="#3、-内存泄露" class="headerlink" title="3、 内存泄露"></a>3、 内存泄露</h3><p>本质上讲, 内存泄露就是不再被需要的内存, 由于某种原因, 无法被释放.</p>
<blockquote>
<p>常见的内存泄露案例</p>
</blockquote>
<ul>
<li>全局变量照成内存泄露</li>
<li>未销毁的定时器和回调函数造成内存泄露</li>
<li>闭包造成内存泄露</li>
</ul>
<h4 id="36-数组对象有哪些原生方法，列举一下"><a href="#36-数组对象有哪些原生方法，列举一下" class="headerlink" title="36.数组对象有哪些原生方法，列举一下"></a>36.数组对象有哪些原生方法，列举一下</h4><ul>
<li>concat、</li>
<li>copyWithin、</li>
<li>fill、</li>
<li>find、</li>
<li>findIndex、</li>
<li>lastIndexOf、</li>
<li>pop、</li>
<li>push、</li>
<li>reverse、</li>
<li>shift、</li>
<li>unshift、</li>
<li>slice、</li>
<li>sort、</li>
<li>splice、</li>
<li>includes、</li>
<li>indexOf、</li>
<li>join、</li>
<li>keys、</li>
<li>entries、</li>
<li>values、</li>
<li>forEach、</li>
<li>filter、</li>
<li>flat、</li>
<li>flatMap、</li>
<li>map、</li>
<li>every、</li>
<li>some、</li>
<li>reduce、</li>
<li>reduceRight</li>
</ul>
<h4 id="37-call、apply、bind三者的用法和区别"><a href="#37-call、apply、bind三者的用法和区别" class="headerlink" title="37.call、apply、bind三者的用法和区别"></a>37.<code>call</code>、<code>apply</code>、<code>bind</code>三者的用法和区别</h4><blockquote>
<p>我们知道，<code>call</code>、<code>apply</code>、<code>bind</code>这三兄弟都是可以改变this指向的，那具体如何使用呢？<br>我们先定义两个对象</p>
</blockquote>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> obj<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
   name<span class="token punctuation">:</span><span class="token string">'Li lei'</span><span class="token punctuation">,</span>
   age<span class="token punctuation">:</span><span class="token number">18</span><span class="token punctuation">,</span>
   intr<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
     console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token string">`我叫$&amp;#123;this.name&amp;#125;,我$&amp;#123;this.age&amp;#125;岁`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
   <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> obj2<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  name<span class="token punctuation">:</span><span class="token string">'Han meimei'</span><span class="token punctuation">,</span>
  age<span class="token punctuation">:</span><span class="token number">20</span><span class="token punctuation">,</span>
  intr<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token string">`I'm $&amp;#123;this.name&amp;#125;,I'm $&amp;#123;this.age&amp;#125; years old`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

obj<span class="token punctuation">.</span><span class="token function">intr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>   
<span class="token comment" spellcheck="true">//我叫Li lei,我18岁</span>
obj2<span class="token punctuation">.</span><span class="token function">intr</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token comment" spellcheck="true">//I'm Han meimei,I'm 20 years old</span>
</code></pre>
<p> 当我们调用<code>obj</code>和<code>obj2</code>中的<code>intr</code>方法时，输出的是各自对象中的<code>name</code>和<code>age</code>，如果我们需要使用<code>obj</code>中的参数执行<code>obj2</code>的<code>intr</code>方法，就可以使用<code>call</code>、<code>apply</code>、<code>bind</code>实现</p>
<h4 id="1-先看一下call"><a href="#1-先看一下call" class="headerlink" title="1)先看一下call"></a>1)先看一下<code>call</code></h4><pre class=" language-javascript"><code class="language-javascript">obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj2<span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token comment" spellcheck="true">//我叫Han meimei,我20岁</span>
obj2<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>obj<span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token comment" spellcheck="true">//I'm Li lei,I'm 18 years old</span></code></pre>
<p>由上可知，当执行第一句时，<code>obj.intr</code>中的<code>this</code>指向发生了改变，指向了<code>obj2</code><br>同理，当执行第二句时，<code>obj2.intr</code>中的<code>this</code>指向了<code>obj</code></p>
<p> 2)再来看看<code>apply</code>和<code>bind</code></p>
<pre class=" language-javascript"><code class="language-javascript">obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span>obj2<span class="token punctuation">)</span><span class="token punctuation">;</span>   
<span class="token comment" spellcheck="true">//我叫Han meimei,我20岁</span>
obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span>obj2<span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>  
<span class="token comment" spellcheck="true">//我叫Han meimei,我20岁</span></code></pre>
<p>可以看到这里<code>apply</code>和<code>call</code>是一样的，但是<code>bind</code>返回的是一个函数，所以需要调用后才执行<code>intr</code>方法</p>
<h4 id="三者传参的区别"><a href="#三者传参的区别" class="headerlink" title="三者传参的区别"></a>三者传参的区别</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> obj<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  name<span class="token punctuation">:</span><span class="token string">'Li lei'</span><span class="token punctuation">,</span>
  intr<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span> age<span class="token punctuation">,</span> city <span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token string">`我叫$&amp;#123;this.name&amp;#125;,我$&amp;#123;age&amp;#125;岁,我来自$&amp;#123;city&amp;#125;`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token keyword">var</span> obj2<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  name<span class="token punctuation">:</span><span class="token string">'Han meimei'</span><span class="token punctuation">,</span>
  intr<span class="token punctuation">:</span><span class="token keyword">function</span><span class="token punctuation">(</span> age<span class="token punctuation">,</span> city <span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token template-string"><span class="token string">`I'm $&amp;#123;this.name&amp;#125;,I'm $&amp;#123;age&amp;#125; years old,I'm from $&amp;#123;city&amp;#125;`</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span> obj2<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token string">'中国'</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>      
 <span class="token comment" spellcheck="true">//我叫Han meimei,我20岁,我来自中国</span>
obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">apply</span><span class="token punctuation">(</span> obj2<span class="token punctuation">,</span> <span class="token punctuation">[</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token string">'中国'</span> <span class="token punctuation">]</span> <span class="token punctuation">)</span><span class="token punctuation">;</span> 
 <span class="token comment" spellcheck="true">//我叫Han meimei,我20岁,我来自中国</span>
obj<span class="token punctuation">.</span>intr<span class="token punctuation">.</span><span class="token function">bind</span><span class="token punctuation">(</span> obj2<span class="token punctuation">,</span> <span class="token number">20</span><span class="token punctuation">,</span> <span class="token string">'中国'</span> <span class="token punctuation">)</span><span class="token punctuation">;</span>       
<span class="token comment" spellcheck="true">//我叫Han meimei,我20岁,我来自中国</span></code></pre>
<p>可以看到<code>call</code>和<code>bind</code>都是独立传递，而<code>apply</code>是以数组传递参数的，参数也可以是方法或对象</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><p><code>call</code>、<code>apply</code>、<code>bind</code>可以将某个函数的<code>this</code>指向修改为传入这三个方法中的第一个参数，其中<code>call</code>、<code>apply</code>会立即执行，<code>bind</code>返回的是一个函数，需调用后执行。</p>
<p>第二个参数是传入要执行的方法中的参数，<code>call</code>、<code>bind</code>是独立传递参数，<code>apply</code>是以数组传递参数的</p>
<p>使用场景：</p>
<p>1、需要改变某个函数的<code>this</code>指向时</p>
<p>2、当参数较少时可以使用<code>call</code>，参数较多可以使用<code>apply</code>以数组的方式传递</p>
<p>3、当需要重复调用时，可以使用<code>bind</code>新定义一个方法</p>
<h4 id="38-requireJS的核心原理是什么？（如何动态加载的？如何避免多次加载的？如何缓存的？）"><a href="#38-requireJS的核心原理是什么？（如何动态加载的？如何避免多次加载的？如何缓存的？）" class="headerlink" title="38.requireJS的核心原理是什么？（如何动态加载的？如何避免多次加载的？如何缓存的？）"></a>38.<code>requireJS</code>的核心原理是什么？（如何动态加载的？如何避免多次加载的？如何缓存的？）</h4><p>核心是<code>js</code>的加载模块，通过正则匹配模块以及模块的依赖关系，保证文件加载的先后顺序，根据文件的路径对加载过的文件做了缓存。</p>
<h4 id="39-AMD-CMD规范区别？"><a href="#39-AMD-CMD规范区别？" class="headerlink" title="39.AMD,CMD规范区别？"></a>39.<code>AMD</code>,<code>CMD</code>规范区别？</h4><p>1.<code>AMD</code> 是 <code>RequireJS</code> 在推广过程中对模块定义的规范化产出。</p>
<p>2.<code>CMD</code> 是 <code>SeaJS</code> 在推广过程中对模块定义的规范化产出。</p>
<h3 id="区别："><a href="#区别：" class="headerlink" title="区别："></a>区别：</h3><p>1、 对于依赖的模块，AMD 是提前执行，CMD 是延迟执行。不过 <code>RequireJS</code> 从 <code>2.0</code> 开始，也改成可以延迟执行（根据写法不同，处理方式不同）。</p>
<p>2、 <code>CMD</code> 推崇依赖就近，<code>AMD</code> 推崇依赖前置。</p>
<p>3、 <code>AMD</code> 的 <code>API</code> 默认是一个当多个用，<code>CMD</code> 的 <code>API</code> 严格区分，推崇职责单一。</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// CMD</span>
<span class="token function">define</span><span class="token punctuation">(</span><span class="token keyword">function</span><span class="token punctuation">(</span>require<span class="token punctuation">,</span> exports<span class="token punctuation">,</span> module<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> a <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'./a'</span><span class="token punctuation">)</span>
    a<span class="token punctuation">.</span><span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
    <span class="token comment" spellcheck="true">// 此处略去 100 行</span>
    <span class="token keyword">var</span> b <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'./b'</span><span class="token punctuation">)</span> 
    <span class="token comment" spellcheck="true">// 依赖可以就近书写</span>
    b<span class="token punctuation">.</span><span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// AMD 默认推荐</span>
<span class="token function">define</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'./a'</span><span class="token punctuation">,</span> <span class="token string">'./b'</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token keyword">function</span><span class="token punctuation">(</span>a<span class="token punctuation">,</span> b<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> 
   <span class="token comment" spellcheck="true">// 依赖必须一开始就写好</span>
    a<span class="token punctuation">.</span><span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token comment" spellcheck="true">// 此处略去 100 行</span>
    b<span class="token punctuation">.</span><span class="token function">doSomething</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span></code></pre>
<h4 id="40-请你谈谈Cookie的弊端？"><a href="#40-请你谈谈Cookie的弊端？" class="headerlink" title="40.请你谈谈Cookie的弊端？"></a>40.请你谈谈<code>Cookie</code>的弊端？</h4><h3 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h3><p>1.IE6或更低版本最多20个cookie</p>
<p>2.IE7和之后的版本最后可以有50个cookie。</p>
<p>3.Firefox最多50个cookie </p>
<p>4.chrome和Safari没有做硬性限制 Opera 会清理近期最少使用的Firefox会随机清理 4096字节，为了兼容性，一般不能超过 IE 提供了一种存储可以持久化用户数据，叫做IE5.0就开始支持。每个数据最多128K，每个域名下最多1M。这个持久化数据放在缓存中，如果缓存没有清理，那么会一直存在。</p>
<h4 id="优点："><a href="#优点：" class="headerlink" title="优点："></a>优点：</h4><p>极高的扩展性和可用性 </p>
<p>1.通过良好的编程，控制保存在cookie中的session对象的大小。 </p>
<p>2.通过加密和安全传输技术（SSL），减少cookie被破解的可能性。</p>
<p>3.只在cookie中存放不敏感数据，即使被盗也不会有重大损失。 </p>
<p>4.控制cookie的生命期，使之不会永远有效。偷盗者很可能拿到一个过期的cookie。 </p>
<h4 id="缺点："><a href="#缺点：" class="headerlink" title="缺点："></a>缺点：</h4><p>1.Cookie数量和长度的限制。每个domain最多只能有20条cookie，每个cookie长度不能超过4KB，否则会被截掉。</p>
<p>2.安全性问题。如果cookie被人拦截了，那人就可以取得所有的session信息。即使加密也与事无补，因为拦截者并不需要知道cookie的意义，他只要原样转发cookie就可以达到目的了。</p>
<p>3.有些状态不可能保存在客户端。例如，为了防止重复提交表单，我们需要在服务器端保存一个计数器。如果我们把这个计数器保存在客户端，那么它起不到任何作用。</p>
<h3 id="41-介绍路由的history"><a href="#41-介绍路由的history" class="headerlink" title="41. 介绍路由的history"></a>41. 介绍路由的<code>history</code></h3><p>history对象保存着用户的上网记录，从浏览器窗口打开的那一刻算起。</p>
<p>出于安全的考虑，开发人员无法得知用户浏览过的URL。</p>
<p>不过，借由用户访问过的页面列表，同样可以在不知道实际URL的情况下实现后退与前进</p>
<h3 id="一、history对象的方法"><a href="#一、history对象的方法" class="headerlink" title="一、history对象的方法"></a>一、history对象的方法</h3><h4 id="go-Stirng-number"><a href="#go-Stirng-number" class="headerlink" title="go(Stirng|number)"></a>go(Stirng|number)</h4><p>使用go方法可以在用户的历史记录中任意跳转，可以向后也可以向前。这个方法接受一个参数，表示向后或向前跳转的页面数的一个整数值。负数表示向后跳转(类似浏览器的后退按钮)，正数表示向前跳转(类似浏览器的前进按钮)。来看下例子</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">//后退一页</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token operator">-</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">//前进一页</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">//前进两页</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span></code></pre>
<p>也可以给go()方法船体一个字符串参数，此时浏览器会跳转到历史记录中包含改字符串的第一个位置，可能后退也可能前进，具体要看哪一个位置最近。如果历史记录中不包含该字符串，则什么都不做。例如：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">//跳转到最近的wrox.com页面</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token string">"wrox.com"</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">//跳转到最近的douban.cn页面</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token string">"douban.cn"</span><span class="token punctuation">)</span></code></pre>
<h4 id="back-和forward"><a href="#back-和forward" class="headerlink" title="back()和forward"></a>back()和forward</h4><p>这两个方法可以来代替go()，模仿浏览器的后退和前进功能<br>back()相当于 go(-1) 后退一个页面<br>forward相当于go(1) 前进一个页面<br>注：接下来几个方法是html5新增的方法</p>
<h3 id="二、html5中history新增的方法"><a href="#二、html5中history新增的方法" class="headerlink" title="二、html5中history新增的方法"></a>二、html5中history新增的方法</h3><p><code>pushState(state,title,url)</code></p>
<p>该方法的作用是 在历史记录中新增一条记录，改变浏览器地址栏的url,但是，不刷新页面。</p>
<h4 id="pushState对象接受三个参数，"><a href="#pushState对象接受三个参数，" class="headerlink" title="pushState对象接受三个参数，"></a>pushState对象接受三个参数，</h4><p>• state：一个与添加的记录相关联的状态对象，主要用于popstate事件。该事件触发时，该对象会传入回调函数。也就是说，浏览器会将这个对象序列化以后保留在本地，重新载入这个页面的时候，可以拿到这个对象。如果不需要这个对象，此处可以填null。<br>• title：新页面的标题。但是，现在所有浏览器都忽视这个参数，所以这里可以填空字符串。<br>• url：新的网址，必须与当前页面处在同一个域。浏览器的地址栏将显示这个网址。<br>举个例子，假设当前网址是hello.com/1.html,使用puchState()方法在浏览记录中添加一个新纪录</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> stateObj<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>foo<span class="token punctuation">:</span><span class="token string">'bar'</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span>starteObj<span class="token punctuation">,</span><span class="token string">''</span><span class="token punctuation">,</span><span class="token string">'2.html'</span><span class="token punctuation">)</span></code></pre>
<p>添加新纪录后，浏览器的地址栏立刻显示`hello.com/2.html,但不会跳转到2.html,也不会检查2.html是否存在，它只是成为浏览历史中的最新记录。</p>
<p>总之，pushState()方法不会触发页面刷新，只是导致history对象发生变化，地址栏会有反应，使用该方法后，就可以使用history.state属性读出状态对象</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> stateObj<span class="token operator">=</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>foo<span class="token punctuation">:</span><span class="token string">'bar'</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span>starteObj<span class="token punctuation">,</span><span class="token string">''</span><span class="token punctuation">,</span><span class="token string">'2.html'</span><span class="token punctuation">)</span>
history<span class="token punctuation">.</span>state <span class="token comment" spellcheck="true">//=> &amp;#123;foo:"bar"&amp;#125;</span></code></pre>
<p>注意：如果pushState的URL参数设置了一个新的hash值，并不会触发hashchange事件。</p>
<h4 id="replaceState-state-title-url"><a href="#replaceState-state-title-url" class="headerlink" title="replaceState(state,title,url)"></a>replaceState(state,title,url)</h4><p>replaceState方法的作用是替换当前的历史记录，其他的都与pushState()方法一模一样。</p>
<p>假定当前网页是example.com/example.html。</p>
<pre class=" language-javascript"><code class="language-javascript">history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>page<span class="token punctuation">:</span> <span class="token number">1</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token string">'title 1'</span><span class="token punctuation">,</span> <span class="token string">'?page=1'</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html?page=1</span>
history<span class="token punctuation">.</span><span class="token function">pushState</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>page<span class="token punctuation">:</span> <span class="token number">2</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token string">'title 2'</span><span class="token punctuation">,</span> <span class="token string">'?page=2'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html?page=2</span>
history<span class="token punctuation">.</span><span class="token function">replaceState</span><span class="token punctuation">(</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>page<span class="token punctuation">:</span> <span class="token number">3</span><span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token string">'title 3'</span><span class="token punctuation">,</span> <span class="token string">'?page=3'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html?page=3</span>
history<span class="token punctuation">.</span><span class="token function">back</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html?page=1</span>
history<span class="token punctuation">.</span><span class="token function">back</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html</span>
history<span class="token punctuation">.</span><span class="token function">go</span><span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>
<span class="token comment" spellcheck="true">// URL 显示为 http://example.com/example.html?page=3</span></code></pre>
<h3 id="三、popstate事件"><a href="#三、popstate事件" class="headerlink" title="三、popstate事件"></a>三、popstate事件</h3><p>popstate事件是window对象上的事件，配合pushState()和replaceState()方法使用。当同一个文档(可以理解为同一个网页，不能跳转，跳转了就不是同一个网页了)的浏览历史出现变化时，就会触发popstate事件。</p>
<p>上面我们说过，调用pushState()或者replaceState()方法都会改变当前的历史记录，仅仅调用pushState()方法或replaceState()方法 ，并不会触发该事件，另外一个条件是用户必须点击浏览器的倒退按钮或者前进按钮，或者使用js调用history.back()或者history.forward()等方法。</p>
<p>所以，记住popstate事件触发的条件</p>
<ol>
<li>处在同一个文档(同一个html页面)</li>
<li>文档的浏览历史(即history对象)发生改变</li>
</ol>
<p>只要符合这两个条件，popstate事件就会触发</p>
<h3 id="具体例子"><a href="#具体例子" class="headerlink" title="具体例子"></a>具体例子</h3><p>//index.html</p>
<pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token script language-javascript">
        window<span class="token punctuation">.</span>onpopstate<span class="token operator">=</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
            <span class="token function">alert</span><span class="token punctuation">(</span><span class="token string">'location '</span><span class="token operator">+</span>document<span class="token punctuation">.</span>location<span class="token operator">+</span><span class="token string">',state '</span><span class="token operator">+</span>jsON<span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>event<span class="token punctuation">.</span>state<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
    <span class="token comment" spellcheck="true">&lt;!--第二步 --></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">onclick</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>window.history.back()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>后退<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">onclick</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>window.history.forward()<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>前进<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>
    <span class="token comment" spellcheck="true">&lt;!--第一步 --></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">onclick</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>window.history.pushState(null,<span class="token punctuation">'</span><span class="token punctuation">'</span>,<span class="token punctuation">'</span>1.html<span class="token punctuation">'</span>)<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>pushState<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>    
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code></pre>
<p>先点击pushState按钮，在点击后退按钮，就会触发popstate事件</p>
<h3 id="再来一个例子"><a href="#再来一个例子" class="headerlink" title="再来一个例子"></a>再来一个例子</h3><p>//index.html</p>
<pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token script language-javascript">
        window<span class="token punctuation">.</span>onpopstate<span class="token operator">=</span><span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
            <span class="token function">alert</span><span class="token punctuation">(</span><span class="token string">'location '</span><span class="token operator">+</span>document<span class="token punctuation">.</span>location<span class="token operator">+</span><span class="token string">',state '</span><span class="token operator">+</span>jsON<span class="token punctuation">.</span><span class="token function">stringify</span><span class="token punctuation">(</span>event<span class="token punctuation">.</span>state<span class="token punctuation">)</span><span class="token punctuation">)</span>
        <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
    </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
    <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>#one<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>#one<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span>   
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code></pre>
<p>直接点击a标签,也可以触发popstate事件</p>
<h3 id="42-如何解决跨域的问题"><a href="#42-如何解决跨域的问题" class="headerlink" title="42.如何解决跨域的问题"></a>42.如何解决跨域的问题</h3><ol>
<li>jsonp：只支持 GET，不支持 POST 请求，不安全 XSS</li>
<li>cors：需要后台配合进行相关的设置</li>
<li>postMessage：配合使用 iframe，需要兼容 IE6、7、8、9</li>
<li>document.domain：仅限于同一域名下的子域</li>
<li>websocket：需要后台配合修改协议，不兼容，需要使用 <a target="_blank" rel="noopener" href="http://socket.io/">http://socket.io</a></li>
<li>proxy：使用代理去避开跨域请求，需要修改 nginx、apache 等的配置(最常用)</li>
</ol>
<h3 id="43-常见Http请求头"><a href="#43-常见Http请求头" class="headerlink" title="43.常见Http请求头"></a>43.常见Http请求头</h3><ol>
<li>Host (主机和端口号)</li>
<li>Connection (链接类型)</li>
<li>Upgrade-Insecure-Requests (升级为 HTTPS 请求)</li>
<li>User-Agent (浏览器名称)</li>
<li>Accept (传输文件类型)</li>
<li>Referer (页面跳转处)</li>
<li>Accept-Encoding（文件编解码格式）</li>
<li>Cookie （Cookie）</li>
<li>x-requested-with :XMLHttpRequest (是 Ajax 异步请求)</li>
</ol>
<h3 id="44-使用过webpack⾥面哪些plugin和loader"><a href="#44-使用过webpack⾥面哪些plugin和loader" class="headerlink" title="44. 使用过webpack⾥面哪些plugin和loader"></a>44. 使用过<code>webpack</code>⾥面哪些<code>plugin</code>和<code>loader</code></h3><h3 id="loader："><a href="#loader：" class="headerlink" title="loader："></a>loader：</h3><ol>
<li>file-loader：把文件输出到一个文件夹中，在代码中通过相对URL引用输入的文件。</li>
<li>url-loader：和file类似，但能在文件很小的情况下以base64方式把文件内容注入到代码中。</li>
<li>image-loader：加载并压缩图片文件。</li>
<li>babel-loader：把ES6转换为ES5。</li>
<li>css-loader：加载CSS，支持模块化、压缩、文件导入等特性。</li>
<li>style-loader：把CSS代码注入到JavaScript中，通过DOM操作去加载CSS。</li>
<li>eslint-loader：通过ESlint检查JavaScript代码。</li>
</ol>
<h3 id="plugin"><a href="#plugin" class="headerlink" title="plugin:"></a>plugin:</h3><ol>
<li>define-plugin：定义环境变量。</li>
<li>commons-chunk-plugin：提取公共代码。</li>
<li>uglifyjs-webpack-plugin：缩小（压缩优化）js文件</li>
</ol>
<h3 id="45-webpack⾥面的插件是怎么实现的"><a href="#45-webpack⾥面的插件是怎么实现的" class="headerlink" title="45. webpack⾥面的插件是怎么实现的"></a>45. <code>webpack</code>⾥面的插件是怎么实现的</h3><p>大部分时候，webpack 对我来说就是个黑盒。</p>
<p>且让我们抛开所有让人畏惧的细节，设想一下，webpack 在构建时会发生什么：</p>
<p>读取入口文件<br>一步一步处理<br>输出各种 assets 文件<br>显然，期间的每一步，应该都是设定好的，而非天马行空。</p>
<p>那么，我们用 webpack 插件扩展的，究竟是什么？</p>
<h3 id="勾子"><a href="#勾子" class="headerlink" title="勾子"></a>勾子</h3><p>勾子用于拦截组件间传递的函数、事件、或消息。</p>
<p>在 webpack 构建过程中，文件从上一环节传递到下一环节，这期间，就有拦截的机会</p>
<h3 id="Tapable"><a href="#Tapable" class="headerlink" title="Tapable"></a>Tapable</h3><p>Tapable 是 webpack 内置各种勾子的实际提供者。</p>
<p>比如，我们调用 SyncHook 来创建一个同步的 hook：</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">import</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span> SyncHook <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">from</span> <span class="token string">'tapable'</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> hook <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">SyncHook</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>创建完 hook 后，我们可以 tap（窃听）该 hook：</p>
<pre class=" language-javascript"><code class="language-javascript">hook<span class="token punctuation">.</span><span class="token function">tap</span><span class="token punctuation">(</span><span class="token string">'MyPlugin'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token comment" spellcheck="true">// 窃听成功</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre>
<p>这样在该 hook 执行时，我们的窃听函数就会执行 - 这正是 webpack 插件的原理，通过 tapable，webpack 主动开放各种 hook。我们只需要 tap 回调到 hook 上，就能保证它们在某个时间点被执行：</p>
<p>hook.call(); // 某个时间点执行该 hook，所有窃听的回调都会被执行<br>除了 SyncHook 外，tapable 还提供了其它类型的勾子，具体可查询文档。</p>
<p>当然，在 webpack 下我们并不直接调用 tapable，因此这里仅就它的原理稍作了解。</p>
<h3 id="webpack-插件写法"><a href="#webpack-插件写法" class="headerlink" title="webpack 插件写法"></a>webpack 插件写法</h3><p>在 webpack 下，它推荐的插件写法是这样：</p>
<pre class=" language-javaScript"><code class="language-javaScript">class MyWebpackPlugin &#123;
  apply(compiler) &#123;
    // 定义一个 class，其中有一个 apply 方法，
    // apply 方法接收 webpack 的 compiler 对象
  &#125;
&#125;</code></pre>
<p>在插件完成后，我们就可以在配置文件中调用插件：</p>
<pre class=" language-javaScript"><code class="language-javaScript">&#123;
  plugins: [
    new MyWebpackPlugin()
  ]
&#125;</code></pre>
<p>webpack 在运行时，会调用我们的插件定义的 apply 方法：</p>
<pre class=" language-javaScript"><code class="language-javaScript">if (Array.isArray(options.plugins)) &#123;
  for (const plugin of options.plugins) &#123;
    if (typeof plugin === 'function') &#123;
      plugin.call(compiler, compiler);
    &#125; else &#123;
      plugin.apply(compiler);
    &#125;
  &#125;
&#125;</code></pre>
<p>于是，我们的勾子们就顺利插入到 webpack 生命周期中。</p>
<h3 id="webpack-勾子"><a href="#webpack-勾子" class="headerlink" title="webpack 勾子"></a>webpack 勾子</h3><p>在知道 webpack 插件的运转原理及 webpack 插件写法之后，我们只要梳理清楚 webpack 所有勾子及勾子触发的时序即可对症下药，在需要的勾子上挂上“窃听器”。</p>
<h3 id="webpack-的勾子分三类："><a href="#webpack-的勾子分三类：" class="headerlink" title="webpack 的勾子分三类："></a>webpack 的勾子分三类：</h3><ul>
<li>Compiler hooks</li>
<li>Compilation hooks</li>
<li>JavascriptParser hooks</li>
</ul>
<p>总共加起来，大约有百来个。一一掌握这百来个勾子并不现实；针对需求，然后查找文档、定位可用的勾子可能更切实际。</p>
<p>原文地址:<a target="_blank" rel="noopener" href="https://blog.zfanw.com/how-webpack-plugin-works/">https://blog.zfanw.com/how-webpack-plugin-works/</a></p>
<h3 id="46-dev-server是怎么跑起来？"><a href="#46-dev-server是怎么跑起来？" class="headerlink" title="46. dev-server是怎么跑起来？"></a>46. <code>dev-server</code>是怎么跑起来？</h3><p>1.安装了webpack以及自己需要使用的loader和plugins，由于webpack-dev-server是个独立的npm包，所以我们需要在npm下安装它</p>
<p>2.在webpack.config.js中进行配置：</p>
<h3 id="devServer中常用的配置对象属性如下："><a href="#devServer中常用的配置对象属性如下：" class="headerlink" title="devServer中常用的配置对象属性如下："></a>devServer中常用的配置对象属性如下：</h3><ol>
<li><p>contentBase：”./”<br>本地服务器在哪个目录搭建页面，一般我们在当前目录即可；</p>
</li>
<li><p>historyApiFallback：true<br>当我们搭建spa应用时非常有用，它使用的是HTML5 History Api，任意的跳转或404响应可以指向 index.html 页面；</p>
</li>
<li><p>inline：true<br>用来支持dev-server自动刷新的配置，webpack有两种模式支持自动刷新，一种是iframe模式，一种是inline模式；使用iframe模式是不需要在devServer进行配置的，只需使用特定的URL格式访问即可；不过我们一般还是常用inline模式，在devServer中对inline设置为true后，当我们启动webpack-dev-server时仍要需要配置inline才能生效，这一点我们之后再说；</p>
</li>
<li><p>hot：true<br>启动webpack热模块替换特性，这里也是坑最多的地方，不少博客都将hot设置了true，我们姑且也设置为true，之后再看；</p>
</li>
<li><p>port：端口号(默认8080)<br>在devServer中设置inline：true后这里也要设置一下！</p>
</li>
</ol>
<h3 id="47-常见项目优化方法"><a href="#47-常见项目优化方法" class="headerlink" title="47.常见项目优化方法"></a>47.常见项目优化方法</h3><h3 id="常见优化方法"><a href="#常见优化方法" class="headerlink" title="常见优化方法"></a>常见优化方法</h3><p>从资源请求数量+代码执行效率两个角度来考虑</p>
<h3 id="DOM结构"><a href="#DOM结构" class="headerlink" title="DOM结构"></a>DOM结构</h3><ol>
<li>样式表放在头部，防止白屏和闪屏</li>
<li>JS脚本放在底部或异步获取，防止阻塞资源加载</li>
<li>使用语义化标签，优化精简DOM结构</li>
<li>减少DOM操作频率</li>
<li>减少重绘与回流<h3 id="JS脚本"><a href="#JS脚本" class="headerlink" title="JS脚本"></a>JS脚本</h3></li>
<li>优化脚本结构，移除重复的脚本</li>
<li>模块就近加载（CMD）</li>
<li>按需加载加载组件和路由</li>
<li>图片懒加载，列表分页</li>
<li>使用节流与防抖减少事件触发频率</li>
<li>尽量使用CSS动画代替js动画，开启硬件加速</li>
<li>资源打包上线</li>
<li>使用打包构建工具（webpack）清除注释，压缩页面资源，js、css、html、图片、字体等等</li>
<li>混淆js代码</li>
<li>分离非业务逻辑相关vendor依赖，使用长缓存缓存和CDN分发网络<h3 id="服务器优化"><a href="#服务器优化" class="headerlink" title="服务器优化"></a>服务器优化</h3></li>
<li>减少Http请求，合并页面资源，js，css单一入口。js特殊可以分为两个文件，一个业务逻辑，一个非业务逻辑</li>
<li>把小图标合成雪碧图，不太适用经常更新的移动端开发</li>
<li>把小的图片，字体等资源base64化</li>
<li>开启GZip压缩，减少资源传输大小</li>
<li>使用强缓存和协商缓存，减少资源重复请求<h3 id="Vue中可以优化的点"><a href="#Vue中可以优化的点" class="headerlink" title="Vue中可以优化的点"></a>Vue中可以优化的点</h3></li>
<li>Vue库dist里面的Runtime-only比Runtime+Compiler小30%</li>
<li>Vue的计算属性会根据依赖的data进行缓存</li>
<li>keep-alive可以缓存常用组件</li>
<li>Vuex中的getter也会根据依赖的state进行缓存</li>
<li>v-for中唯一key的使用</li>
<li>Vue全局错误处理errorHandle</li>
<li>Vue路由懒加载</li>
<li>Vue组件动态加载<h3 id="React中可以优化的点"><a href="#React中可以优化的点" class="headerlink" title="React中可以优化的点"></a>React中可以优化的点</h3></li>
<li>在constructor改变this指向代替箭头函数和render内绑定this，避免函数作为props带来不必要的rerender</li>
<li>shouldComponentUpdate，减少不不必要的rerender</li>
<li>PureComponent高性能组件只响应引用数据的深拷贝</li>
<li>使用唯一key优化list diff</li>
<li>合并setState操作，减少虚拟dom对比频率</li>
<li>React路由动态加载react-loadable</li>
</ol>
<h3 id="48-抽取公共文件是怎么配置的"><a href="#48-抽取公共文件是怎么配置的" class="headerlink" title="48. 抽取公共文件是怎么配置的"></a>48. 抽取公共文件是怎么配置的</h3><p>在不明白CommonsChunkPlugin的使用情况下，直接上手webpack4的splitChunks，实在是难上加难。为了能更好的理解splitChunks的使用，必须出个题目，练练手，才能从中有所收获（下面的题目不考虑实际应用场景）：</p>
<p>从指定入口文件中提取公共文件</p>
<p>CommonsChunkPlugin的实现：</p>
<pre class=" language-javaScript"><code class="language-javaScript">entry: &#123;
        index:'./src/index.js',
        index1:'./src/index1.js',
        index2:'./src/index2.js'
&#125;,
plugins: [
    new CommonsChunkPlugin(&#123;
        name:"common1",
        chunks:['index','index1','index2']
    &#125;)
]</code></pre>
<p>其中index和index1以及index2都是打包的入口文件。</p>
<h3 id="49-项目中如何处理安全问题"><a href="#49-项目中如何处理安全问题" class="headerlink" title="49. 项目中如何处理安全问题"></a>49. 项目中如何处理安全问题</h3><p>随着大前端的快速发展，各种技术不断更新，前端的安全问题也值得我们重视。<br>今天我们来聊一聊前端常见的7个安全方面问题：</p>
<ol>
<li>iframe</li>
<li>opener</li>
<li>CSRF（跨站请求伪造）</li>
<li>XSS（跨站脚本攻击）</li>
<li>ClickJacking（点击劫持）</li>
<li>HSTS（HTTP严格传输安全）</li>
<li>CND劫持</li>
</ol>
<h3 id="1）、iframe"><a href="#1）、iframe" class="headerlink" title="1）、iframe"></a>1）、iframe</h3><h4 id="a、如何让自己的网站不被其他网站的-iframe-引用？"><a href="#a、如何让自己的网站不被其他网站的-iframe-引用？" class="headerlink" title="a、如何让自己的网站不被其他网站的 iframe 引用？"></a>a、如何让自己的网站不被其他网站的 iframe 引用？</h4><p>// 检测当前网站是否被第三方iframe引用<br>// 若相等证明没有被第三方引用，若不等证明被第三方引用。当发现被引用时强制跳转百度。<br>if(top.location != self.location){<br>    top.location.href = ‘<a target="_blank" rel="noopener" href="http://www.baidu.com&/#39;">http://www.baidu.com&#39;</a><br>}</p>
<h4 id="b、如何禁用，被使用的-iframe-对当前网站某些操作？"><a href="#b、如何禁用，被使用的-iframe-对当前网站某些操作？" class="headerlink" title="b、如何禁用，被使用的 iframe 对当前网站某些操作？"></a>b、如何禁用，被使用的 iframe 对当前网站某些操作？</h4><p>sandbox是html5的新属性，主要是提高iframe安全系数。iframe因安全问题而臭名昭著，这主要是因为iframe常被用于嵌入到第三方中，然后执行某些恶意操作。<br>现在有一场景：我的网站需要 iframe 引用某网站，但是不想被该网站操作DOM、不想加载某些js（广告、弹框等）、当前窗口被强行跳转链接等，我们可以设置 sandbox 属性。如使用多项用空格分隔。</p>
<ul>
<li>allow-same-origin：允许被视为同源，即可操作父级DOM或cookie等</li>
<li>allow-top-navigation：允许当前iframe的引用网页通过url跳转链接或加载</li>
<li>allow-forms：允许表单提交</li>
<li>allow-scripts：允许执行脚本文件</li>
<li>allow-popups：允许浏览器打开新窗口进行跳转</li>
<li>“”：设置为空时上面所有允许全部禁止</li>
</ul>
<h3 id="2）、opener"><a href="#2）、opener" class="headerlink" title="2）、opener"></a>2）、opener</h3><p>如果在项目中需要 打开新标签 进行跳转一般会有两种方式<br>参考地址：<a target="_blank" rel="noopener" href="https://paper.seebug.org/538/">https://paper.seebug.org/538/</a></p>
<pre><code>1) HTML -&gt; &lt;a target=&#39;_blank&#39; href=&#39;http://www.baidu.com&#39;&gt;
2)  JS  -&gt; window.open(&#39;http://www.baidu.com&#39;)</code></pre>
<ul>
<li>这两种方式看起来没有问题，但是存在漏洞。</li>
<li>通过这两种方式打开的页面可以使用 window.opener 来访问源页面的 window 对象。</li>
<li>场景：A 页面通过 <a> 或 window.open 方式，打开 B 页面。但是 B 页面存在恶意代码如下：</li>
<li>window.opener.location.replace(‘<a target="_blank" rel="noopener" href="https://www.baidu.com&/#39;">https://www.baidu.com&#39;</a>) 【此代码仅针对打开新标签有效】</li>
<li>此时，用户正在浏览新标签页，但是原来网站的标签页已经被导航到了百度页面。</li>
<li>恶意网站可以伪造一个足以欺骗用户的页面，使得进行恶意破坏。</li>
<li>即使在跨域状态下 opener 仍可以调用 location.replace 方法。<pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">target</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>_blank<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span><span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">target</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>_blank<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span><span class="token punctuation">"</span></span> <span class="token attr-name">rel</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>noopener noreferrer nofollow<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>a标签跳转url<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span></code></pre>
通过 rel 属性进行控制：<br>noopener：会将 window.opener 置空，从而源标签页不会进行跳转（存在浏览器兼容问题）<br>noreferrer：兼容老浏览器/火狐。禁用HTTP头部Referer属性（后端方式）。<br>nofollow：SEO权重优化</li>
</ul>
<h3 id="b、window-open"><a href="#b、window-open" class="headerlink" title="b、window.open()"></a>b、window.open()</h3><pre><code>&lt;button onclick=&#39;openurl(&quot;http://www.baidu.com&quot;)&#39;&gt;click跳转&lt;/button&gt;</code></pre>
<pre class=" language-javaScript"><code class="language-javaScript">function openurl(url) &#123;
    var newTab = window.open();
    newTab.opener = null;
    newTab.location = url;
&#125;</code></pre>
<h4 id="3）、CSRF-XSRF（跨站请求伪造）"><a href="#3）、CSRF-XSRF（跨站请求伪造）" class="headerlink" title="3）、CSRF / XSRF（跨站请求伪造）"></a>3）、CSRF / XSRF（跨站请求伪造）</h4><p>你可以这么理解 CSRF 攻击：攻击者盗用了你的身份，以你的名义进行恶意请求。它能做的事情有很多包括：以你的名义发送邮件、发信息、盗取账号、购买商品、虚拟货币转账等。</p>
<p>总结起来就是：个人隐私暴露及财产安全问题。</p>
<ul>
<li>阐述 CSRF 攻击思想：（核心2和3）</li>
<li>1、浏览并登录信任网站（举例：淘宝）</li>
<li>2、登录成功后在浏览器产生信息存储（举例：cookie）</li>
<li>3、用户在没有登出淘宝的情况下，访问危险网站</li>
<li>4、危险网站中存在恶意代码，代码为发送一个恶意请求（举例：购买商品/余额转账）</li>
<li>5、携带刚刚在浏览器产生的信息进行恶意请求</li>
<li>6、淘宝验证请求为合法请求（区分不出是否是该用户发送）</li>
<li>7、达到了恶意目标</li>
</ul>
<h4 id="防御措施（推荐添加token-HTTP头自定义属性）"><a href="#防御措施（推荐添加token-HTTP头自定义属性）" class="headerlink" title="防御措施（推荐添加token / HTTP头自定义属性）"></a>防御措施（推荐添加token / HTTP头自定义属性）</h4><ul>
<li>涉及到数据修改操作严格使用 post 请求而不是 get 请求</li>
<li>HTTP 协议中使用 Referer 属性来确定请求来源进行过滤（禁止外域）</li>
<li>请求地址添加 token ，使黑客无法伪造用户请求</li>
<li>HTTP 头自定义属性验证（类似上一条）</li>
<li>显示验证方式：添加验证码、密码等</li>
</ul>
<h3 id="4）、XSS-CSS（跨站脚本攻击）"><a href="#4）、XSS-CSS（跨站脚本攻击）" class="headerlink" title="4）、XSS/CSS（跨站脚本攻击）"></a>4）、XSS/CSS（跨站脚本攻击）</h3><p>XSS又叫CSS（Cross Site Script），跨站脚本攻击：攻击者在目标网站植入恶意脚本（js / html），用户在浏览器上运行时可以获取用户敏感信息（cookie / session）、修改web页面以欺骗用户、与其他漏洞相结合形成蠕虫等。</p>
<p>浏览器遇到 html 中的 script 标签时，会解析并执行其中的js代码。举例：</p>
<p><img src="https://yangyunhaiimagesoss.oss-cn-shanghai.aliyuncs.com/2010211739_1603273192085.png"></p>
<p>针对这种情况，我们对特殊字符进行转译就好了（vue/react等主流框架已经避免类似问题，vue举例：不能在template中写script标签，无法在js中通过ref或append等方式动态改变或添加script标签）</p>
<h4 id="XSS类型："><a href="#XSS类型：" class="headerlink" title="XSS类型："></a>XSS类型：</h4><ol>
<li>持久型XSS：将脚本植入到服务器上，从而导致每个访问的用户都会执行</li>
<li>非持久型XSS：对个体用户某url的参数进行攻击</li>
</ol>
<h4 id="防御措施（对用户输入内容和服务端返回内容进行过滤和转译）"><a href="#防御措施（对用户输入内容和服务端返回内容进行过滤和转译）" class="headerlink" title="防御措施（对用户输入内容和服务端返回内容进行过滤和转译）"></a>防御措施（对用户输入内容和服务端返回内容进行过滤和转译）</h4><ol>
<li>现代大部分浏览器都自带 XSS 筛选器，vue / react 等成熟框架也对 XSS 进行一些防护</li>
<li>即便如此，我们在开发时也要注意和小心</li>
<li>对用户输入内容和服务端返回内容进行过滤和转译</li>
<li>重要内容加密传输</li>
<li>合理使用get/post等请求方式</li>
<li>对于URL携带参数谨慎使用</li>
<li>我们无法做到彻底阻止，但是能增加黑客攻击成本，当成本与利益不符时自然会降低风险</li>
</ol>
<h4 id="5）、ClickJacking（点击劫持）"><a href="#5）、ClickJacking（点击劫持）" class="headerlink" title="5）、ClickJacking（点击劫持）"></a>5）、ClickJacking（点击劫持）</h4><p>ClickJacking 翻译过来被称为点击劫持。一般会利用透明 iframe 覆盖原网页诱导用户进行某些操作达成目的。</p>
<h4 id="防御措施"><a href="#防御措施" class="headerlink" title="防御措施"></a>防御措施</h4><p>在HTTP投中加入 X-FRAME-OPTIONS 属性，此属性控制页面是否可被嵌入 iframe 中【DENY：不能被所有网站嵌套或加载；SAMEORIGIN：只能被同域网站嵌套或加载；ALLOW-FROM URL：可以被指定网站嵌套或加载。】<br>判断当前网页是否被 iframe 嵌套（详情在第一条 firame 中）</p>
<h4 id="6）、HSTS（HTTP-Strict-Transport-Security：HTTP严格传输安全）"><a href="#6）、HSTS（HTTP-Strict-Transport-Security：HTTP严格传输安全）" class="headerlink" title="6）、HSTS（HTTP Strict Transport Security：HTTP严格传输安全）"></a>6）、HSTS（HTTP Strict Transport Security：HTTP严格传输安全）</h4><p>网站接受从 HTTP 请求跳转到 HTTPS 请求的做法，例如我们输入“<a target="_blank" rel="noopener" href="http://www.baidu.com”或“www.baidu.com”最终都会被302重定向到“https//www.baidu.com%E2%80%9D%E3%80%82%E8%BF%99%E5%B0%B1%E5%AD%98%E5%9C%A8%E5%AE%89%E5%85%A8%E9%A3%8E%E9%99%A9%EF%BC%8C%E5%BD%93%E6%88%91%E4%BB%AC%E7%AC%AC%E4%B8%80%E6%AC%A1%E9%80%9A%E8%BF%87">http://www.baidu.com”或“www.baidu.com”最终都会被302重定向到“https://www.baidu.com”。这就存在安全风险，当我们第一次通过</a> HTTP 或域名进行访问时，302重定向有可能会被劫持，篡改成一个恶意或钓鱼网站。</p>
<p>HSTS：通知浏览器此网站禁止使用 HTTP 方式加载，浏览器应该自动把所有尝试使用 HTTP 的请求自动替换为 HTTPS 进行请求。用户首次访问时并不受 HSTS 保护，因为第一次还未形成链接。我们可以通过 浏览器预置HSTS域名列表 或 将HSTS信息加入到域名系统记录中，来解决第一次访问的问题。</p>
<h3 id="7）、CDN劫持"><a href="#7）、CDN劫持" class="headerlink" title="7）、CDN劫持"></a>7）、CDN劫持</h3><p>出于性能考虑，前端应用通常会把一些静态资源存放到CDN（Content Delivery Networks）上面，例如 js 脚本和 style 文件。这么做可以显著提高前端应用的访问速度，但与此同时却也隐含了一个新的安全风险。如果攻击者劫持了CDN，或者对CDN中的资源进行了污染，攻击者可以肆意篡改我们的前端页面，对用户实施攻击。</p>
<p>现在的CDN以支持SRI为荣，script 和 link 标签有了新的属性 integrity，这个属性是为了防止校验资源完整性来判断是否被篡改。它通过 验证获取文件的哈希值是否和你提供的哈希值一样来判断资源是否被篡改。</p>
<p>使用 SRI 需要两个条件：一是要保证 资源同域 或开启跨域，二是在<code>&lt;script&gt;</code>中 提供签名 以供校验。</p>
<p><img src="https://pic1.zhimg.com/80/v2-335779c835a8855274c15dc67177a4d4_720w.png"></p>
<p>integrity 属性分为两个部分，第一部分是指定哈希值的生成算法（例：sha384），第二部分是经过编码的实际哈希值，两者之前用一个短横(-)来分隔<br>这个属性也存在兼容问题</p>
<p><img src="https://pic2.zhimg.com/80/v2-b261b0bffcdf1d30d10c84bdccbe78a9_720w.jpg"></p>
<h5 id="50、为什么要语义化？"><a href="#50、为什么要语义化？" class="headerlink" title="50、为什么要语义化？"></a>50、为什么要语义化？</h5><p>为了在没有<code>CSS</code>的情况下，页面也能呈现出很好地内容结构、代码结构</p>
<p>用户体验：例如<code>title</code>、<code>alt</code>用于解释名词或解释图片信息、<code>label</code>标签的活用；</p>
<p>有利于<code>SEO</code> ：和搜索引擎建立良好沟通，有助于爬虫抓取更多的有效信息：</p>
<p>爬虫依赖于标签来确定上下文和各个关键字的权重；<br>方便其他设备解析（如屏幕阅读器、盲人阅读器、移动设备）以意义的方式来渲染网页；</p>
<p>便于团队开发和维护，语义化更具可读性，是下一步吧网页的重要动向，遵循<code>W3C</code>标准的团队都遵循这个标准，可以减少差异化</p>
<h4 id="51-文件上传如何做断点续传"><a href="#51-文件上传如何做断点续传" class="headerlink" title="51.文件上传如何做断点续传?"></a>51.文件上传如何做断点续传?</h4><h3 id="前端"><a href="#前端" class="headerlink" title="前端"></a>前端</h3><p>前端大文件上传网上的大部分文章已经给出了解决方案</p>
<p>核心是利用 Blob.prototype.slice 方法，和数组的 slice 方法相似，调用的 slice 方法可以返回原文件的某个切片</p>
<p>这样我们就可以根据预先设置好的切片最大数量将文件切分为一个个切片，然后借助 http 的可并发性，同时上传多个切片，这样从原本传一个大文件，变成了同时传多个小的文件切片，可以大大减少上传时间</p>
<p>另外由于是并发，传输到服务端的顺序可能会发生变化，所以我们还需要给每个切片记录顺序</p>
<h3 id="服务端"><a href="#服务端" class="headerlink" title="服务端"></a>服务端</h3><p>服务端需要负责接受这些切片，并在接收到所有切片后合并切片</p>
<p>这里又引伸出两个问题</p>
<p>何时合并切片，即切片什么时候传输完成 如何合并切片</p>
<p>第一个问题需要前端进行配合，前端在每个切片中都携带切片最大数量的信息，当服务端接受到这个数量的切片时自动合并，也可以额外发一个请求主动通知服务端进行切片的合并</p>
<p>第二个问题，具体如何合并切片呢？这里可以使用 nodejs 的 api fs.appendFileSync，它可以同步地将数据追加到指定文件，也就是说，当服务端接受到所有切片后，先创建一个最终的文件，然后将所有切片逐步合并到这个文件中</p>
<h4 id="52-new运算符的实现机制？"><a href="#52-new运算符的实现机制？" class="headerlink" title="52.new运算符的实现机制？"></a>52.<code>new</code>运算符的实现机制？</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">var</span> new2 <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>func<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> o <span class="token operator">=</span> Object<span class="token punctuation">.</span><span class="token function">create</span><span class="token punctuation">(</span>func<span class="token punctuation">.</span>prototype<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">var</span> k <span class="token operator">=</span> func<span class="token punctuation">.</span><span class="token function">call</span><span class="token punctuation">(</span>o<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">typeof</span> k <span class="token operator">===</span> <span class="token string">'object'</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> k<span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        <span class="token keyword">return</span> o<span class="token punctuation">;</span>
    <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h4 id="53-描述一下EventLoop的执行过程"><a href="#53-描述一下EventLoop的执行过程" class="headerlink" title="53.描述一下EventLoop的执行过程"></a>53.描述一下<code>EventLoop</code>的执行过程</h4><ul>
<li><p>一开始整个脚本作为一个宏任务执行</p>
</li>
<li><p>执行过程中同步代码直接执行，宏任务进入宏任务队列，微任务进入微任务队列</p>
</li>
<li><p>当前宏任务执行完出队，检查微任务列表，有则依次执行，直到全部执行完</p>
</li>
<li><p>执行浏览器UI线程的渲染工作</p>
</li>
<li><p>检查是否有Web Worker任务，有则执行</p>
</li>
<li><p>执行完本轮的宏任务，回到2，依此循环，直到宏任务和微任务队列都为空</p>
</li>
</ul>
<h4 id="54-Promise和Callback有什么区别"><a href="#54-Promise和Callback有什么区别" class="headerlink" title="54.Promise和Callback有什么区别?"></a>54.<code>Promise</code>和<code>Callback</code>有什么区别?</h4><p>相比于<code>callback，Promise</code> 具有更易读的代码组织形式（链式结构调用），更好的异常处理方式（在调用 <code>Promise</code> 的末尾添加上一个catch方法捕获异常即可），以及异步操作并行处理的能力（<code>Promise.all()</code> <code>Promise.race()</code>等）。</p>
<p><code>callback</code>最大的问题就是我们通常说的回调地狱,一旦业务逻辑复杂了,我们不得不使用大量的嵌套回调代码,可维护性很低.</p>
<h4 id="55-用js写一个数组扁平化函数"><a href="#55-用js写一个数组扁平化函数" class="headerlink" title="55.用js写一个数组扁平化函数"></a>55.用<code>js</code>写一个数组扁平化函数</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token comment" spellcheck="true">// reduce</span>
<span class="token keyword">function</span> <span class="token function">flatten</span><span class="token punctuation">(</span>arr <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>  
  <span class="token keyword">return</span> arr<span class="token punctuation">.</span><span class="token function">reduce</span><span class="token punctuation">(</span><span class="token punctuation">(</span>result<span class="token punctuation">,</span> item<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> result<span class="token punctuation">.</span><span class="token function">concat</span><span class="token punctuation">(</span>Array<span class="token punctuation">.</span><span class="token function">isArray</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span> <span class="token operator">?</span> <span class="token function">flatten</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span> <span class="token punctuation">:</span> item<span class="token punctuation">)</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>

<span class="token comment" spellcheck="true">// (toString | join) &amp; split(利用数组的toString或者join,将数组转化为字符串)</span>
<span class="token keyword">function</span> <span class="token function">flatten</span><span class="token punctuation">(</span>arr <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> arr<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">split</span><span class="token punctuation">(</span><span class="token string">','</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">map</span><span class="token punctuation">(</span>item <span class="token operator">=</span><span class="token operator">></span> <span class="token function">Number</span><span class="token punctuation">(</span>item<span class="token punctuation">)</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h3 id="56-csrf跨站攻击怎么解决"><a href="#56-csrf跨站攻击怎么解决" class="headerlink" title="56.csrf跨站攻击怎么解决"></a>56.<code>csrf</code>跨站攻击怎么解决</h3><p><code>CSRF</code>, 跨站请求伪造,它可以在用户毫不知情的情况下以用户名义伪造请求发送给受攻击站点，从而对用户或者网站造成攻击. 预防措施如下:</p>
<p>服务器端验证<code>HTTP Referer</code>字段, <code>Referer</code>记录了该<code>HTTP</code>请求的来源地址•在请求地址中添加<code>token</code>并验证•在<code>HTTP</code>头中自定义属性并验证</p>
<h4 id="57-用js实现数组随机取数，每次返回的值都不一样"><a href="#57-用js实现数组随机取数，每次返回的值都不一样" class="headerlink" title="57.用js实现数组随机取数，每次返回的值都不一样"></a>57.用<code>js</code>实现数组随机取数，每次返回的值都不一样</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">function</span> <span class="token function">getUniqueItems</span><span class="token punctuation">(</span>arr<span class="token punctuation">,</span> num<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> temp <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> index <span class="token keyword">in</span> arr<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      temp<span class="token punctuation">.</span><span class="token function">push</span><span class="token punctuation">(</span>arr<span class="token punctuation">[</span>index<span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
  <span class="token keyword">let</span> res <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">let</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i<span class="token operator">&lt;</span>num<span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
      <span class="token keyword">if</span> <span class="token punctuation">(</span>temp<span class="token punctuation">.</span>length<span class="token operator">></span><span class="token number">0</span><span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
          <span class="token keyword">let</span> arrIndex <span class="token operator">=</span> Math<span class="token punctuation">.</span><span class="token function">floor</span><span class="token punctuation">(</span>Math<span class="token punctuation">.</span><span class="token function">random</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">*</span>temp<span class="token punctuation">.</span>length<span class="token punctuation">)</span><span class="token punctuation">;</span>
          res<span class="token punctuation">[</span>i<span class="token punctuation">]</span> <span class="token operator">=</span> temp<span class="token punctuation">[</span>arrIndex<span class="token punctuation">]</span><span class="token punctuation">;</span>
          temp<span class="token punctuation">.</span><span class="token function">splice</span><span class="token punctuation">(</span>arrIndex<span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span> <span class="token keyword">else</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
        <span class="token keyword">break</span><span class="token punctuation">;</span>
      <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
  <span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
  <span class="token keyword">return</span> res<span class="token punctuation">;</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<h3 id="58-Promise的基础题"><a href="#58-Promise的基础题" class="headerlink" title="58.Promise的基础题"></a>58.<code>Promise</code>的基础题</h3><pre class=" language-javaScript"><code class="language-javaScript">const promise1 = new Promise((resolve, reject) => &#123;
  console.log('promise1')
&#125;)
console.log('1', promise1);</code></pre>
<h3 id="过程分析："><a href="#过程分析：" class="headerlink" title="过程分析："></a>过程分析：</h3><p>从上至下，先遇到<code>new Promise</code>，执行该构造函数中的代码<code>promise1</code><br>然后执行同步代码1，此时<code>promise1</code>没有被<code>resolve</code>或者<code>reject</code>，因此状态还是<code>pending</code></p>
<h3 id="结果："><a href="#结果：" class="headerlink" title="结果："></a>结果：</h3><pre class=" language-javaScript"><code class="language-javaScript">'promise1'
'1' Promise&#123;<pending>&#125;</code></pre>
<h4 id="59-Promise的基础题"><a href="#59-Promise的基础题" class="headerlink" title="59.Promise的基础题"></a>59.<code>Promise</code>的基础题</h4><pre class=" language-javaScript"><code class="language-javaScript">const promise = new Promise((resolve, reject) => &#123;
  console.log(1);
  resolve('success')
  console.log(2);
&#125;);
promise.then(() => &#123;
  console.log(3);
&#125;);
console.log(4);
</code></pre>
<h3 id="过程分析：-1"><a href="#过程分析：-1" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>从上至下，先遇到new Promise，执行其中的同步代码1</li>
<li>再遇到resolve(‘success’)， 将promise的状态改为了resolved并且将值保存下来</li>
<li>继续执行同步代码2</li>
<li>跳出promise，往下执行，碰到promise.then这个微任务，将其加入微任务队列</li>
<li>执行同步代码4</li>
<li>本轮宏任务全部执行完毕，检查微任务队列，发现promise.then这个微任务且状态为1. resolved，执行它。</li>
</ol>
<h3 id="结果：-1"><a href="#结果：-1" class="headerlink" title="结果："></a>结果：</h3><pre><code>1 2 4 3</code></pre>
<h3 id="60-Promise的基础题"><a href="#60-Promise的基础题" class="headerlink" title="60.Promise的基础题"></a>60.<code>Promise</code>的基础题</h3><pre class=" language-javaScript"><code class="language-javaScript">const promise = new Promise((resolve, reject) => &#123;
  console.log(1);
  console.log(2);
&#125;);
promise.then(() => &#123;
  console.log(3);
&#125;);
console.log(4);</code></pre>
<h3 id="过程分析：-2"><a href="#过程分析：-2" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>和题目二相似，只不过在promise中并没有resolve或者reject</li>
<li>因此promise.then并不会执行，它只有在被改变了状态之后才会执行</li>
</ol>
<h3 id="结果：-2"><a href="#结果：-2" class="headerlink" title="结果："></a>结果：</h3><pre><code>1 2 4</code></pre>
<h4 id="61-Promise的基础题"><a href="#61-Promise的基础题" class="headerlink" title="61.Promise的基础题"></a>61.<code>Promise</code>的基础题</h4><pre class=" language-javaScript"><code class="language-javaScript">const fn = () => (new Promise((resolve, reject) => &#123;
  console.log(1);
  resolve('success')
&#125;))
fn().then(res => &#123;
  console.log(res)
&#125;)
console.log('start')
</code></pre>
<h3 id="过程分析：-3"><a href="#过程分析：-3" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>这道题里最先执行的是’start’吗  ？</li>
<li>请仔细看看哦，fn函数它是直接返回了一个new Promise的，而且fn函数的调用是在start之前，所以它里面的内容应该会先执行。</li>
</ol>
<h3 id="结果：-3"><a href="#结果：-3" class="headerlink" title="结果："></a>结果：</h3><pre><code>1
&#39;start&#39;
&#39;success&#39;
</code></pre>
<h4 id="62-Promise的基础题"><a href="#62-Promise的基础题" class="headerlink" title="62.Promise的基础题"></a>62.<code>Promise</code>的基础题</h4><pre class=" language-javaScript"><code class="language-javaScript">const fn = () =>
  new Promise((resolve, reject) => &#123;
    console.log(1);
    resolve("success");
  &#125;);
console.log("start");
fn().then(res => &#123;
  console.log(res);
&#125;);</code></pre>
<h3 id="过程分析：-4"><a href="#过程分析：-4" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>是的，现在start就在1之前打印出来了，因为fn函数是之后执行的。</li>
<li>注意⚠️：之前我们很容易就以为看到new Promise()就执行它的第一个参数函数了，其实这是不对的，就像这两道题中，我们得注意它是不是被包裹在函数当中，如果是的话，只有在函数调用的时候才会执行。</li>
</ol>
<h3 id="结果：-4"><a href="#结果：-4" class="headerlink" title="结果："></a>结果：</h3><pre><code>&quot;start&quot;
1
&quot;success&quot;</code></pre>
<h4 id="63-Promise结合setTimeout"><a href="#63-Promise结合setTimeout" class="headerlink" title="63.Promise结合setTimeout"></a>63.<code>Promise</code>结合<code>setTimeout</code></h4><pre class=" language-javaScript"><code class="language-javaScript">console.log('start')
setTimeout(() => &#123;
  console.log('time')
&#125;)
Promise.resolve().then(() => &#123;
  console.log('resolve')
&#125;)
console.log('end')

</code></pre>
<h3 id="过程分析：-5"><a href="#过程分析：-5" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>刚开始整个脚本作为一个宏任务来执行，对于同步代码直接压入执行栈进行执行，因此先打印出start和end。</li>
<li>setTimout作为一个宏任务被放入宏任务队列(下一个)</li>
<li>Promise.then作为一个微任务被放入微任务队列</li>
<li>本次宏任务执行完，检查微任务，发现Promise.then，执行它<br>接下来进入下一个宏任务，发现setTimeout，执行。</li>
</ol>
<h3 id="结果：-5"><a href="#结果：-5" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;start&#39;
&#39;end&#39;
&#39;resolve&#39;
&#39;time&#39;</code></pre>
<h4 id="64-Promise结合setTimeout"><a href="#64-Promise结合setTimeout" class="headerlink" title="64.Promise结合setTimeout"></a>64.<code>Promise</code>结合<code>setTimeout</code></h4><pre class=" language-javaScript"><code class="language-javaScript">const promise = new Promise((resolve, reject) => &#123;
  console.log(1);
  setTimeout(() => &#123;
    console.log("timerStart");
    resolve("success");
    console.log("timerEnd");
  &#125;, 0);
  console.log(2);
&#125;);
promise.then((res) => &#123;
  console.log(res);
&#125;);
console.log(4);
</code></pre>
<h3 id="过程分析：-6"><a href="#过程分析：-6" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>从上至下，先遇到new Promise，执行该构造函数中的代码1</li>
<li>然后碰到了定时器，将这个定时器中的函数放到下一个宏任务的延迟队列中等待执行</li>
<li>执行同步代码2</li>
<li>跳出promise函数，遇到promise.then，但其状态还是为pending，这里理解为先不执行</li>
<li>执行同步代码4</li>
<li>一轮循环过后，进入第二次宏任务，发现延迟队列中有setTimeout定时器，执行它</li>
<li>首先执行timerStart，然后遇到了resolve，将promise的状态改为resolved且保存结果并将1. 之前的promise.then推入微任务队列</li>
<li>继续执行同步代码timerEnd</li>
<li>宏任务全部执行完毕，查找微任务队列，发现promise.then这个微任务，执行它。</li>
</ol>
<h3 id="结果：-6"><a href="#结果：-6" class="headerlink" title="结果："></a>结果：</h3><pre><code>1
2
4
&quot;timerStart&quot;
&quot;timerEnd&quot;
&quot;success&quot;</code></pre>
<h4 id="65-Promise结合setTimeout"><a href="#65-Promise结合setTimeout" class="headerlink" title="65.Promise结合setTimeout"></a>65.<code>Promise</code>结合<code>setTimeout</code></h4><pre class=" language-javaScript"><code class="language-javaScript">Promise.resolve().then(() => &#123;
  console.log('promise1');
  const timer2 = setTimeout(() => &#123;
    console.log('timer2')
  &#125;, 0)
&#125;);
const timer1 = setTimeout(() => &#123;
  console.log('timer1')
  Promise.resolve().then(() => &#123;
    console.log('promise2')
  &#125;)
&#125;, 0)
console.log('start');
</code></pre>
<h3 id="过程分析：-7"><a href="#过程分析：-7" class="headerlink" title="过程分析："></a>过程分析：</h3><p>这道题稍微的难一些，在promise中执行定时器，又在定时器中执行promise；</p>
<p>并且要注意的是，这里的Promise是直接resolve的，而之前的new Promise不一样。<br>(偷偷告诉你，这道题往下一点有流程图)</p>
<p>因此过程分析为：</p>
<ol>
<li>刚开始整个脚本作为第一次宏任务来执行，我们将它标记为宏1，从上至下执行</li>
<li>遇到Promise.resolve().then这个微任务，将then中的内容加入第一次的微任务队列标记为微1</li>
<li>遇到定时器timer1，将它加入下一次宏任务的延迟列表，标记为宏2，等待执行(先不管里面是什么内容)</li>
<li>执行宏1中的同步代码start</li>
<li>第一次宏任务(宏1)执行完毕，检查第一次的微任务队列(微1)，发现有一个promise.then这个微任务需要执行</li>
<li>执行打印出微1中同步代码promise1，然后发现定时器timer2，将它加入宏2的后面，标记为宏3</li>
<li>第一次微任务队列(微1)执行完毕，执行第二次宏任务(宏2)，首先执行同步代码timer1</li>
<li>然后遇到了promise2这个微任务，将它加入此次循环的微任务队列，标记为微2</li>
<li>宏2中没有同步代码可执行了，查找本次循环的微任务队列(微2)，发现了promise2，执行它</li>
<li>第二轮执行完毕，执行宏3，打印出timer2</li>
</ol>
<h3 id="结果：-7"><a href="#结果：-7" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;start&#39;
&#39;promise1&#39;
&#39;timer1&#39;
&#39;promise2&#39;
&#39;timer2&#39;
</code></pre>
<h4 id="66-Promise结合setTimeout"><a href="#66-Promise结合setTimeout" class="headerlink" title="66.Promise结合setTimeout"></a>66.<code>Promise</code>结合<code>setTimeout</code></h4><pre class=" language-javaScript"><code class="language-javaScript">const promise1 = new Promise((resolve, reject) => &#123;
  setTimeout(() => &#123;
    resolve('success')
  &#125;, 1000)
&#125;)
const promise2 = promise1.then(() => &#123;
  throw new Error('error!!!')
&#125;)
console.log('promise1', promise1)
console.log('promise2', promise2)
setTimeout(() => &#123;
  console.log('promise1', promise1)
  console.log('promise2', promise2)
&#125;, 2000)
</code></pre>
<h3 id="过程分析：-8"><a href="#过程分析：-8" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>从上至下，先执行第一个new Promise中的函数，碰到setTimeout将它加入下一个宏任务列表</li>
<li>跳出new Promise，碰到promise1.then这个微任务，但其状态还是为pending，这里理解为先不执行</li>
<li>promise2是一个新的状态为pending的Promise</li>
<li>执行同步代码console.log(‘promise1’)，且打印出的promise1的状态为pending</li>
<li>执行同步代码console.log(‘promise2’)，且打印出的promise2的状态为pending</li>
<li>碰到第二个定时器，将其放入下一个宏任务列表</li>
<li>第一轮宏任务执行结束，并且没有微任务需要执行，因此执行第二轮宏任务</li>
<li>先执行第一个定时器里的内容，将promise1的状态改为resolved且保存结果并将之前的promise1.then推入微任务队列</li>
<li>该定时器中没有其它的同步代码可执行，因此执行本轮的微任务队列，也就是promise1.then，它抛出了一个错误，且将promise2的状态设置为了rejected</li>
<li>第一个定时器执行完毕，开始执行第二个定时器中的内容</li>
<li>打印出’promise1’，且此时promise1的状态为resolved</li>
<li>打印出’promise2’，且此时promise2的状态为rejected</li>
</ol>
<h3 id="结果：-8"><a href="#结果：-8" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;promise1&#39; Promise&#123;&lt;pending&gt;&#125;
&#39;promise2&#39; Promise&#123;&lt;pending&gt;&#125;
test5.html:102 Uncaught (in promise) Error: error!!! at test.html:102
&#39;promise1&#39; Promise&#123;&lt;resolved&gt;: &quot;success&quot;&#125;
&#39;promise2&#39; Promise&#123;&lt;rejected&gt;: Error: error!!!&#125;</code></pre>
<h3 id="67-async-await的几道题"><a href="#67-async-await的几道题" class="headerlink" title="67.async/await的几道题"></a>67.<code>async/await</code>的几道题</h3><pre class=" language-javaScript"><code class="language-javaScript">async function async1() &#123;
  console.log("async1 start");
  await async2();
  console.log("async1 end");
&#125;
async function async2() &#123;
  console.log("async2");
&#125;
async1();
console.log('start')</code></pre>
<h3 id="过程分析：-9"><a href="#过程分析：-9" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>首先一进来是创建了两个函数的，我们先不看函数的创建位置，而是看它的调用位置<br>发现async1函数被调用了，然后去看看调用的内容</li>
<li>执行函数中的同步代码async1 start，之后碰到了await，它会阻塞async1后面代码的执行，1. 因此会先去执行async2中的同步代码async2，然后跳出async1</li>
<li>跳出async1函数后，执行同步代码start</li>
<li>在一轮宏任务全部执行完之后，再来执行刚刚await后面的内容async1 end。</li>
</ol>
<p>在这里，你可以理解为「紧跟着await后面的语句相当于放到了new Promise中，下一行及之后的语句相当于放在Promise.then中」。</p>
<h3 id="结果：-9"><a href="#结果：-9" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;async1 start&#39;
&#39;async2&#39;
&#39;start&#39;
&#39;async1 end&#39;
</code></pre>
<h3 id="68-async-await的几道题"><a href="#68-async-await的几道题" class="headerlink" title="68.async/await的几道题"></a>68.<code>async/await</code>的几道题</h3><p>现在将async结合定时器看看。</p>
<p>给题目一中的 async2函数中加上一个定时器：</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1() &#123;
  console.log("async1 start");
  await async2();
  console.log("async1 end");
&#125;
async function async2() &#123;
  setTimeout(() => &#123;
    console.log('timer')
  &#125;, 0)
  console.log("async2");
&#125;
async1();
console.log("start")
</code></pre>
<h3 id="过程分析：-10"><a href="#过程分析：-10" class="headerlink" title="过程分析："></a>过程分析：</h3><p>没错，定时器始终还是最后执行的，它被放到下一条宏任务的延迟队列中。</p>
<h3 id="结果：-10"><a href="#结果：-10" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;async1 start&#39;
&#39;async2&#39;
&#39;start&#39;
&#39;async1 end&#39;
&#39;timer&#39;</code></pre>
<h3 id="69-async-await的几道题"><a href="#69-async-await的几道题" class="headerlink" title="69.async/await的几道题"></a>69.<code>async/await</code>的几道题</h3><p>来吧，小伙伴们，让我们多加几个定时器看看。😁</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1() &#123;
  console.log("async1 start");
  await async2();
  console.log("async1 end");
  setTimeout(() => &#123;
    console.log('timer1')
  &#125;, 0)
&#125;
async function async2() &#123;
  setTimeout(() => &#123;
    console.log('timer2')
  &#125;, 0)
  console.log("async2");
&#125;
async1();
setTimeout(() => &#123;
  console.log('timer3')
&#125;, 0)
console.log("start")

</code></pre>
<h3 id="过程分析：-11"><a href="#过程分析：-11" class="headerlink" title="过程分析："></a>过程分析：</h3><p>思考一下🤔，执行结果会是什么？</p>
<p>其实如果你能做到这里了，说明你前面的那些知识点也都掌握了，我就不需要太过详细的步骤分析了。</p>
<h3 id="结果：-11"><a href="#结果：-11" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;async1 start&#39;
&#39;async2&#39;
&#39;start&#39;
&#39;async1 end&#39;
&#39;timer2&#39;
&#39;timer3&#39;
&#39;timer1&#39;
</code></pre>
<p>定时器谁先执行，你只需要关注谁先被调用的以及延迟时间是多少，这道题中延迟时间都是0，所以只要关注谁先被调用的。。</p>
<h3 id="70-async-await的几道题"><a href="#70-async-await的几道题" class="headerlink" title="70.async/await的几道题"></a>70.<code>async/await</code>的几道题</h3><p>来吧，小伙伴们，让我们多加几个定时器看看。😁</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1 () &#123;
  console.log('async1 start');
  await new Promise(resolve => &#123;
    console.log('promise1')
  &#125;)
  console.log('async1 success');
  return 'async1 end'
&#125;
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')</code></pre>
<h3 id="过程分析：-12"><a href="#过程分析：-12" class="headerlink" title="过程分析："></a>过程分析：</h3><p>这道题目比较有意思，大家要注意了。</p>
<p>在async1中await后面的Promise是没有返回值的，也就是它的状态始终是pending状态，因此相当于一直在await，await，await却始终没有响应…</p>
<p>所以在await之后的内容是不会执行的，也包括async1后面的 .then。</p>
<h3 id="结果：-12"><a href="#结果：-12" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;script start&#39;
&#39;async1 start&#39;
&#39;promise1&#39;
&#39;script end&#39;</code></pre>
<h3 id="71-async-await的几道题"><a href="#71-async-await的几道题" class="headerlink" title="71.async/await的几道题"></a>71.<code>async/await</code>的几道题</h3><p>让我们给上一题中的Promise加上resolve：</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1 () &#123;
  console.log('async1 start');
  await new Promise(resolve => &#123;
    console.log('promise1')
    resolve('promise1 resolve')
  &#125;).then(res => console.log(res))
  console.log('async1 success');
  return 'async1 end'
&#125;
console.log('srcipt start')
async1().then(res => console.log(res))
console.log('srcipt end')
</code></pre>
<h3 id="过程分析：-13"><a href="#过程分析：-13" class="headerlink" title="过程分析："></a>过程分析：</h3><p>现在Promise有了返回值了，因此await后面的内容将会被执行：</p>
<h3 id="结果：-13"><a href="#结果：-13" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;script start&#39;
&#39;async1 start&#39;
&#39;promise1&#39;
&#39;script end&#39;
&#39;promise1 resolve&#39;
&#39;async1 success&#39;
&#39;async1 end&#39;
</code></pre>
<h3 id="72-async-await的几道题"><a href="#72-async-await的几道题" class="headerlink" title="72.async/await的几道题"></a>72.<code>async/await</code>的几道题</h3><p>让我们给上一题中的Promise加上resolve：</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1 () &#123;
  console.log('async1 start');
  await new Promise(resolve => &#123;
    console.log('promise1')
    resolve('promise resolve')
  &#125;)
  console.log('async1 success');
  return 'async1 end'
&#125;
console.log('srcipt start')
async1().then(res => &#123;
  console.log(res)
&#125;)
new Promise(resolve => &#123;
  console.log('promise2')
  setTimeout(() => &#123;
    console.log('timer')
  &#125;)
&#125;)

</code></pre>
<h3 id="过程分析：-14"><a href="#过程分析：-14" class="headerlink" title="过程分析："></a>过程分析：</h3><p>这道题应该也不难，不过有一点需要注意的，在async1中的new Promise它的resovle的值和async1().then()里的值是没有关系的，很多小伙伴可能看到resovle(‘promise resolve’)就会误以为是async1().then()中的返回值。</p>
<h3 id="结果：-14"><a href="#结果：-14" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;script start&#39;
&#39;async1 start&#39;
&#39;promise1&#39;
&#39;promise2&#39;
&#39;async1 success&#39;
&#39;async1 end&#39;
&#39;timer&#39;</code></pre>
<h3 id="73-async-await的几道题"><a href="#73-async-await的几道题" class="headerlink" title="73.async/await的几道题"></a>73.<code>async/await</code>的几道题</h3><p>让我们给上一题中的Promise加上resolve：</p>
<pre class=" language-javaScript"><code class="language-javaScript">async function async1() &#123;
  console.log("async1 start");
  await async2();
  console.log("async1 end");
&#125;

async function async2() &#123;
  console.log("async2");
&#125;

console.log("script start");

setTimeout(function() &#123;
  console.log("setTimeout");
&#125;, 0);

async1();

new Promise(function(resolve) &#123;
  console.log("promise1");
  resolve();
&#125;).then(function() &#123;
  console.log("promise2");
&#125;);
console.log('script end')
</code></pre>
<h3 id="过程分析：-15"><a href="#过程分析：-15" class="headerlink" title="过程分析："></a>过程分析：</h3><p>有了上面👆几题做基础，相信你很快也能答上来了。</p>
<p>(这道题最后async1 end和promise2的顺序其实在网上饱受争议，我这里使用浏览器Chrome V80，Node v12.16.1的执行结果都是上面这个答案)</p>
<h3 id="结果：-15"><a href="#结果：-15" class="headerlink" title="结果："></a>结果：</h3><pre><code>&#39;script start&#39;
&#39;async1 start&#39;
&#39;async2&#39;
&#39;promise1&#39;
&#39;script end&#39;
&#39;async1 end&#39;
&#39;promise2&#39;
&#39;setTimeout&#39;
</code></pre>
<h3 id="74-综合题"><a href="#74-综合题" class="headerlink" title="74.综合题"></a>74.综合题</h3><p>上面👆的题目都是被我拆分着说一些功能点，现在让我们来做一些比较难的综合题吧。</p>
<pre class=" language-javaScript"><code class="language-javaScript">const first = () => (new Promise((resolve, reject) => &#123;
    console.log(3);
    let p = new Promise((resolve, reject) => &#123;
        console.log(7);
        setTimeout(() => &#123;
            console.log(5);
            resolve(6);
            console.log(p)
        &#125;, 0)
        resolve(1);
    &#125;);
    resolve(2);
    p.then((arg) => &#123;
        console.log(arg);
    &#125;);
&#125;));
first().then((arg) => &#123;
    console.log(arg);
&#125;);
console.log(4);
</code></pre>
<h3 id="过程分析：-16"><a href="#过程分析：-16" class="headerlink" title="过程分析："></a>过程分析：</h3><ol>
<li>第一段代码定义的是一个函数，所以我们得看看它是在哪执行的，发现它在4之前，所以可以来看看first函数里面的内容了。(这一步有点类似于题目1.5)</li>
<li>函数first返回的是一个new Promise()，因此先执行里面的同步代码3</li>
<li>接着又遇到了一个new Promise()，直接执行里面的同步代码7</li>
<li>执行完7之后，在p中，遇到了一个定时器，先将它放到下一个宏任务队列里不管它，接着向下走</li>
<li>碰到了resolve(1)，这里就把p的状态改为了resolved，且返回值为1，不过这里也先不执行</li>
<li>跳出p，碰到了resolve(2)，这里的resolve(2)，表示的是把first函数返回的那个Promise的状态改了，也先不管它。</li>
<li>然后碰到了p.then，将它加入本次循环的微任务列表，等待执行</li>
<li>跳出first函数，遇到了first().then()，将它加入本次循环的微任务列表(p.then的后面执行)<br>然后执行同步代码4</li>
<li>本轮的同步代码全部执行完毕，查找微任务列表，发现p.then和first().then()，依次执行，打印出1和2</li>
<li>本轮任务执行完毕了，发现还有一个定时器没有跑完，接着执行这个定时器里的内容，执行同步代码5</li>
<li>然后又遇到了一个resolve(6)，它是放在p里的，但是p的状态在之前已经发生过改变了，因此这里就不会再改变，也就是说resolve(6)相当于没任何用处，因此打印出来的p为<code>Promise&#123;&lt;resolved&gt;: 1&#125;</code>。</li>
</ol>
<h3 id="结果：-16"><a href="#结果：-16" class="headerlink" title="结果："></a>结果：</h3><pre><code>3
7
4
1
2
5
Promise&#123;&lt;resolved&gt;: 1&#125;</code></pre>
<p>刷题，刷到这的小伙伴，一定要给自己一朵花，我录题的时候都吐了。。。。。</p>
<p><img src="https://user-gold-cdn.xitu.io/2020/2/28/1708bb1c9abe9b51?imageView2/0/w/1280/h/960/format/webp/ignore-error/1"></p>
<h3 id="75-使用Promise实现每隔1秒输出1-2-3"><a href="#75-使用Promise实现每隔1秒输出1-2-3" class="headerlink" title="75.使用Promise实现每隔1秒输出1,2,3"></a>75.使用<code>Promise</code>实现每隔1秒输出<code>1,2,3</code></h3><p>这道题比较简单的一种做法是可以用<code>Promise</code>配合着<code>reduce</code>不停的在<code>promise</code>后面叠加<code>.then</code>，请看下面的代码：</p>
<pre class=" language-javaScript"><code class="language-javaScript">const arr = [1, 2, 3]
arr.reduce((p, x) => &#123;
  return p.then(() => &#123;
    return new Promise(r => &#123;
      setTimeout(() => r(console.log(x)), 1000)
    &#125;)
  &#125;)
&#125;, Promise.resolve())</code></pre>
<p>或者你可以更简单一点写：</p>
<pre class=" language-javaScript"><code class="language-javaScript">const arr = [1, 2, 3]
arr.reduce((p, x) => p.then(() => new Promise(r => setTimeout(() => r(console.log(x)), 1000))), Promise.resolve())</code></pre>
<h3 id="76-使用Promise实现红绿灯交替重复亮"><a href="#76-使用Promise实现红绿灯交替重复亮" class="headerlink" title="76.使用Promise实现红绿灯交替重复亮"></a>76.使用<code>Promise</code>实现红绿灯交替重复亮</h3><p>红灯3秒亮一次，黄灯2秒亮一次，绿灯1秒亮一次；如何让三个灯不断交替重复亮灯？（<code>用Promise</code>实现）三个亮灯函数已经存在：</p>
<pre class=" language-javaScript"><code class="language-javaScript">function red() &#123;
    console.log('red');
&#125;
function green() &#123;
    console.log('green');
&#125;
function yellow() &#123;
    console.log('yellow');
&#125;</code></pre>
<h3 id="答案："><a href="#答案：" class="headerlink" title="答案："></a>答案：</h3><pre class=" language-javaScript"><code class="language-javaScript">function red() &#123;
  console.log("red");
&#125;
function green() &#123;
  console.log("green");
&#125;
function yellow() &#123;
  console.log("yellow");
&#125;
const light = function (timer, cb) &#123;
  return new Promise(resolve => &#123;
    setTimeout(() => &#123;
      cb()
      resolve()
    &#125;, timer)
  &#125;)
&#125;
const step = function () &#123;
  Promise.resolve().then(() => &#123;
    return light(3000, red)
  &#125;).then(() => &#123;
    return light(2000, green)
  &#125;).then(() => &#123;
    return light(1000, yellow)
  &#125;).then(() => &#123;
    return step()
  &#125;)
&#125;

step();</code></pre>
<h3 id="77-封装一个异步加载图片的方法"><a href="#77-封装一个异步加载图片的方法" class="headerlink" title="77.封装一个异步加载图片的方法"></a>77.封装一个异步加载图片的方法</h3><p>这个相对简单一些，只需要在图片的<code>onload</code>函数中，使用<code>resolve</code>返回一下就可以了。</p>
<h3 id="来看看具体代码："><a href="#来看看具体代码：" class="headerlink" title="来看看具体代码："></a>来看看具体代码：</h3><pre class=" language-javaScript"><code class="language-javaScript">function loadImg(url) &#123;
  return new Promise((resolve, reject) => &#123;
    const img = new Image();
    img.onload = function() &#123;
      console.log("一张图片加载完成");
      resolve(img);
    &#125;;
    img.onerror = function() &#123;
        reject(new Error('Could not load image at' + url));
    &#125;;
    img.src = url;
  &#125;);</code></pre>
<h3 id="78-pc、h5一套代码和两套代码的优劣"><a href="#78-pc、h5一套代码和两套代码的优劣" class="headerlink" title="78.pc、h5一套代码和两套代码的优劣?"></a>78.<code>pc、h5</code>一套代码和两套代码的优劣?</h3><h4 id="优势"><a href="#优势" class="headerlink" title="优势"></a>优势</h4><p>1.降低了开发人员成本<br>2.提升了维护成本</p>
<h4 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h4><p>1.如果页面过于复杂的话，会造成css文件过大<br>2.需要兼容更多的应用端<br>3.因为pc端需要考虑seo，而h5对seo要求较低，所以会造成技术选型不是很匹配。</p>
<h3 id="79-0等于什么？为什么？"><a href="#79-0等于什么？为什么？" class="headerlink" title="79.[] == 0等于什么？为什么？"></a>79.<code>[] == 0</code>等于什么？为什么？</h3><p>这道题考察的知识点为：javascript隐式转换</p>
<blockquote>
<p>JavaScript中的ToPrimitive规则:</p>
</blockquote>
<p><img src="https://yangyunhaiimagesoss.oss-cn-shanghai.aliyuncs.com/2011091700_1604912443324.png"></p>
<p>当对象类型和原始类型做相等比较时，对象类型会依照<code>ToPrimitive</code>规则转换为原始类型</p>
<p><code>ToPrimitive</code>指对象类型类型（如：对象、数组）转换为原始类型的操作。</p>
<p>当对象类型需要被转为原始类型时，它会先查找对象的<code>valueOf</code>方法，如果<code>valueOf</code>方法返回原始类型的值，则<code>ToPrimitive</code>的结果就是这个值</p>
<p>如果<code>valueOf</code>不存在或者<code>valueOf</code>方法返回的不是原始类型的值，就会尝试调用对象的<code>toString</code>方法，也就是会遵循对象的<code>ToString</code>规则，然后使用<code>toString</code>的返回值作为<code>ToPrimitive</code>的结果。如果valueOf和toString都没有返回原始类型的值，则会抛出异常。</p>
<p>字符串和数字比较时，会先转为数字类型，空字符为<code>0</code></p>
<p>所以:</p>
<pre class=" language-javascript"><code class="language-javascript"><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">valueOf</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">==</span> <span class="token number">0</span>
↓
<span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token operator">==</span> <span class="token number">0</span>
↓
<span class="token function">Number</span><span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span> <span class="token operator">==</span> <span class="token number">0</span>
↓
<span class="token string">""</span><span class="token operator">==</span><span class="token number">0</span></code></pre>
<h4 id="80-点击一个input依次触发的事件"><a href="#80-点击一个input依次触发的事件" class="headerlink" title="80.点击一个input依次触发的事件?"></a>80.点击一个<code>input</code>依次触发的事件?</h4><pre class=" language-javascript"><code class="language-javascript"><span class="token keyword">const</span> text <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">getElementById</span><span class="token punctuation">(</span><span class="token string">'text'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
text<span class="token punctuation">.</span>onclick <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'onclick'</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
text<span class="token punctuation">.</span>onfocus <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'onfocus'</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
text<span class="token punctuation">.</span>onmousedown <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'onmousedown'</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span>
text<span class="token punctuation">.</span>onmouseenter <span class="token operator">=</span> <span class="token keyword">function</span> <span class="token punctuation">(</span>e<span class="token punctuation">)</span> <span class="token operator">&amp;</span>#<span class="token number">123</span><span class="token punctuation">;</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'onmouseenter'</span><span class="token punctuation">)</span>
<span class="token operator">&amp;</span>#<span class="token number">125</span><span class="token punctuation">;</span></code></pre>
<blockquote>
<p>答案：</p>
</blockquote>
<pre><code>&#39;onmouseenter&#39;
&#39;onmousedown&#39;
&#39;onfocus&#39;
&#39;onclick&#39;</code></pre>
<h4 id="81-什么是微前端？"><a href="#81-什么是微前端？" class="headerlink" title="81.什么是微前端？"></a>81.什么是微前端？</h4><p>微前端（Micro-Frontends）是一种类似于微服务的架构，它将微服务的理念应用于浏览器端，即将 Web 应用由单一的单体应用转变为多个小型前端应用聚合为一的应用。各个前端应用还可以独立运行、独立开发、独立部署。微前端不是单纯的前端框架或者工具，而是一套架构体系</p>
<h2 id="为什么会有微前端"><a href="#为什么会有微前端" class="headerlink" title="为什么会有微前端"></a>为什么会有微前端</h2><p>任何新技术的产生都是为了解决现有场景和需求下的技术痛点，微前端也不例外：</p>
<h3 id="拆分和细化："><a href="#拆分和细化：" class="headerlink" title="拆分和细化："></a>拆分和细化：</h3><p>当下前端领域，单页面应用（SPA）是非常流行的项目形态之一，而随着时间的推移以及应用功能的丰富，单页应用变得不再单一而是越来越庞大也越来越难以维护，往往是改一处而动全身，由此带来的发版成本也越来越高。微前端的意义就是将这些庞大应用进行拆分，并随之解耦，每个部分可以单独进行维护和部署，提升效率。</p>
<h3 id="整合历史系统："><a href="#整合历史系统：" class="headerlink" title="整合历史系统："></a>整合历史系统：</h3><p>在不少的业务中，或多或少会存在一些历史项目，这些项目大多以采用老框架类似（Backbone.js，Angular.js 1）的B端管理系统为主，介于日常运营，这些系统需要结合到新框架中来使用还不能抛弃，对此我们也没有理由浪费时间和精力重写旧的逻辑。而微前端可以将这些系统进行整合，在基本不修改来逻辑的同时来同时兼容新老两套系统并行运行。</p>
<h3 id="实现微前端有哪些方案"><a href="#实现微前端有哪些方案" class="headerlink" title="实现微前端有哪些方案"></a>实现微前端有哪些方案</h3><ul>
<li>Mooa：基于Angular的微前端服务框架</li>
<li>Single-Spa：最早的微前端框架，兼容多种前端技术栈。</li>
<li>Qiankun：基于Single-Spa，阿里系开源微前端框架。</li>
<li>Icestark：阿里飞冰微前端框架，兼容多种前端技术栈。</li>
<li>Ara Framework：由服务端渲染延伸出的微前端框架。</li>
</ul>
<h3 id="注意事项"><a href="#注意事项" class="headerlink" title="注意事项"></a>注意事项</h3><p>1.iconffont 字体在子应用无法加载<br>原因：</p>
<blockquote>
<p>shadow dom 是不支持@font-face 的，所以当引入 iconfont 的时候，尽管可以引入样式，但由于字体文件是不存在的，所以相对应的图标也无法展示。</p>
</blockquote>
<h3 id="方案："><a href="#方案：" class="headerlink" title="方案："></a>方案：</h3><ul>
<li>把字体文件放在主应用加载</li>
<li>使用通用的字体文件</li>
</ul>
<p>2.dom的查询方法找不到指定的元素</p>
<h3 id="原因："><a href="#原因：" class="headerlink" title="原因："></a>原因：</h3><p>shadow dom 内的元素是被隔离的元素，故 document下查询的方法例如，querySelector、getElementsById 等是获取不到 shadow dom 内元素的。</p>
<h3 id="方案：-1"><a href="#方案：-1" class="headerlink" title="方案："></a>方案：</h3><p>代理 document 下各个查询元素的方法，使用子应用传入的容器，即外面的 shadow dom一层查询。具体使用可以参考乾坤的这个方法 initGlobalState。</p>
<p>3.组件库动态创建的元素无法使用自己的样式</p>
<h3 id="原因：-1"><a href="#原因：-1" class="headerlink" title="原因："></a>原因：</h3><p>有些对话框或提示窗是通过document.body.appendChild添加的，所以 shadow dom 内引入的 CSS 是无法作用到外面元素的。</p>
<h3 id="方案：-2"><a href="#方案：-2" class="headerlink" title="方案："></a>方案：</h3><p>代理document.body.appendChild方法，即把新加的元素添加到 shadow dom容器下，而不是最外面的 body节点下。</p>
<h3 id="补充："><a href="#补充：" class="headerlink" title="补充："></a>补充：</h3><p>类似的问题都可以往这个方向靠，看是不是shadow dom节点或者dom方法的问题。</p>
<p>4.第三方引入的 JS 不生效</p>
<h3 id="原因：-2"><a href="#原因：-2" class="headerlink" title="原因："></a>原因：</h3><p>有些 JS 文件本身是个立即执行函数，或者会动态的创建 scipt 标签，但是所有获取资源的请求是被乾坤劫持处理，所以都不会正常执行，也不会在 window 下面挂载相应的变量，自然在取值调用的时候也不存在这个变量。</p>
<h3 id="方案：-3"><a href="#方案：-3" class="headerlink" title="方案："></a>方案：</h3><p>参考乾坤的 issue，子应用向body添加script标签失败</p>
<p>5.webpack-dev-server 代理访问的接口 cookie 丢失</p>
<h3 id="原因：-3"><a href="#原因：-3" class="headerlink" title="原因："></a>原因：</h3><p>在主应用的端口下请求子应用的端口，存在跨域，axios 默认情况下跨域是不携带 cookie 的，假如把 axios 的 withCredential设置为 true（表示跨域携带 cookie），那么子应用需要设置跨域访问头Access-Control-Allow-Origin（在 devServer 下配置 header）为指定的域名，但不能设置为*，这时候同时存在主应用和子应用端口发出的请求，而跨域访问头只能设置一个地址，就导致无法代理指定服务器接口。</p>
<h3 id="方案：-4"><a href="#方案：-4" class="headerlink" title="方案："></a>方案：</h3><p>子应用接口请求的端口使用主应用接口请求的端口，使用主应用的配置代理请求</p>
<pre class=" language-javaScript"><code class="language-javaScript">// 主应用
devServer: &#123;
    ...
    port: 9600
    proxy: &#123;
        // 代理配置
    &#125;
&#125;
// 子应用
devServer: &#123;
    ...
    port: 9600, // 使用主应用的页面访问端口
&#125;</code></pre>
<h3 id="82-两个请求并行发送，如果其中一个请求出错，就用默认值代替，怎么实现"><a href="#82-两个请求并行发送，如果其中一个请求出错，就用默认值代替，怎么实现" class="headerlink" title="82.两个请求并行发送，如果其中一个请求出错，就用默认值代替，怎么实现?"></a>82.两个请求并行发送，如果其中一个请求出错，就用默认值代替，怎么实现?</h3><pre class=" language-javaScript"><code class="language-javaScript">// 方法1（类似这种）
import awaitTo from "await-to-js";
const p1=new Promise(()=>&#123;&#125;);
const p2=new Promise(()=>&#123;&#125;);
const [errors,results]=awaitTo(Promise.all([p1,p2]));
// 如果出错给errors赋默认值就可以了


// 方法2（类似这种）+ ajax-hook 最完美
const apiDefaultValues=&#123;
  "/getLit":1
&#125;
const httpGet=(options)=>&#123;
  return new Promise((resolve, reject) => &#123;
  axios.get().then(res => &#123;
    if (res) &#123;
      resolve(1);
    &#125; else &#123;
      reject(2);
    &#125;
    &#125;)
    .catch(error => &#123;
      resolve(apiDefaultValues[options.url])
    &#125;);
  &#125;)
&#125;</code></pre>
<h3 id="83-页面有两个相同的请求怎么复用"><a href="#83-页面有两个相同的请求怎么复用" class="headerlink" title="83.页面有两个相同的请求怎么复用?"></a>83.页面有两个相同的请求怎么复用?</h3><p>Vuex+localStorage</p>
<h3 id="84-跨域通信有哪些？"><a href="#84-跨域通信有哪些？" class="headerlink" title="84.跨域通信有哪些？"></a>84.跨域通信有哪些？</h3><ul>
<li>postMessage</li>
<li>document.domain</li>
<li>WebSocket</li>
<li>JSONP</li>
<li>window.name</li>
<li>location.hash</li>
<li>http-proxy</li>
</ul>
<h3 id="85-什么是懒加载？"><a href="#85-什么是懒加载？" class="headerlink" title="85.什么是懒加载？"></a>85.什么是懒加载？</h3><p>懒加载是一种在页面加载时延迟加载一些非关键资源的技术，换句话说就是按需加载。</p>
<ul>
<li>图片懒加载：scroll 滚动懒加载</li>
<li>元素懒加载IntersectionObserver()</li>
<li>路由懒加载：import()</li>
</ul>
<h3 id="86-commonjs-和-es-module区别？"><a href="#86-commonjs-和-es-module区别？" class="headerlink" title="86.commonjs 和 es module区别？"></a>86.commonjs 和 es module区别？</h3><ul>
<li>commonJs是被加载的时候运行，esModule是编译的时候运行</li>
<li>commonJs输出的是值的浅拷贝，esModule输出值的引用</li>
<li>commentJs具有缓存。在第一次被加载时，会完整运行整个文件并输出一个对象，拷贝（浅拷贝）在内存中。下次加载文件时，直接从内存中取值</li>
</ul>
<h3 id="87-tree-sharking原理？"><a href="#87-tree-sharking原理？" class="headerlink" title="87.tree sharking原理？"></a>87.tree sharking原理？</h3><h2 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h2><h3 id="利用ES6模块的特点"><a href="#利用ES6模块的特点" class="headerlink" title="利用ES6模块的特点:"></a>利用ES6模块的特点:</h3><ul>
<li>只能作为模块顶层的语句出现</li>
<li>import的模块名只能是字符串常量，不能动态引入模块</li>
<li>import binding 是immutable的，引入的模块不能再进行修改</li>
</ul>
<blockquote>
<p>虽然tree shaking的概念在1990就提出了，但直到ES6的ES6-style模块出现后才真正被利用起来。这是因为treeshaking只能在静态modules下工作。ECMAScript6模块加载是静态的,因此整个依赖树可以被静态地推导出解析语法树。所以在ES6中使用tree shaking是非常容易的。而且, tree shaking不仅支持import/export级别，而且也支持statement(声明)级别。</p>
</blockquote>
<p>在ES6以前，我们可以使用CommonJS引入模块:require()，这种引入是动态的，也意味着我们可以基于条件来导入需要的代码:</p>
<pre class=" language-javaScript"><code class="language-javaScript">let dynamicModule;
// 动态导入
if(condition) &#123;
    myDynamicModule = require("foo");
&#125; else &#123;
    myDynamicModule = require("bar");
&#125;</code></pre>
<p>CommonJS的动态特性模块意味着tree shaking不适用。因为它是不可能确定哪些模块实际运行之前是需要的或者是不需要的。在ES6中，进入了完全静态的导入语法:import。这也意味着下面的导入是不可行的:</p>
<pre class=" language-javaScript"><code class="language-javaScript">// 不可行，ES6 的import是完全静态的
if(condition) &#123;
    myDynamicModule = require("foo");
&#125; else &#123;
    myDynamicModule = require("bar");
&#125;

只能通过导入所有的包后再进行条件获取
import foo from "foo";
import bar from "bar";

if(condition) &#123;
    // foo.xxxx
&#125; else &#123;
    // bar.xxx
&#125;</code></pre>
<p>ES6的import语法完美可以使用tree shaking，因为可以在代码不运行的情况下就能分析出不需要的代码。</p>
<h2 id="如何使用"><a href="#如何使用" class="headerlink" title="如何使用"></a>如何使用</h2><p>从webpack 2开始支持实现了Tree shaking特性，webpack 2正式版本内置支持ES2015模块（也叫做harmony模块）和未引用模块检测能力。新的webpack 4正式版本，扩展了这个检测能力，通过package.json的sideEffects属性作为标记，向compiler提供提示，表明项目中的哪些文件是“pure(纯的 ES2015模块)”，由此可以安全地删除文件中未使用的部分。</p>
<p>如果使用的是webpack4,只需要将mode设置为production即可开启tree shaking</p>
<pre class=" language-javaScript"><code class="language-javaScript">entry: './src/index.js',
mode: 'production', // 设置为production模式
output: &#123;
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
&#125;</code></pre>
<p>如果是使用webpack2,可能你会发现tree shaking不起作用。因为babel会将代码编译成CommonJs模块，而treeshaking不支持CommonJs。所以需要配置不转义:</p>
<pre class=" language-javaScript"><code class="language-javaScript">options: &#123; 
  presets: [ [ 
  'es2015', &#123; 
    modules: false 
  &#125; 
 ] ] 
&#125;</code></pre>
<h2 id="关于side-effects-副作用"><a href="#关于side-effects-副作用" class="headerlink" title="关于side effects(副作用)"></a>关于side effects(副作用)</h2><p>side effects是指那些当import的时候会执行一些动作，但是不一定会有任何export。比如ployfill,ployfills不对外暴露方法给主程序使用。</p>
<p>tree shaking不能自动的识别哪些代码属于side effects ,因此手动指定这些代码显得非常重要，如果不指定可能会出现一些意想不到的问题。</p>
<p>在webapck中，是通过package.json的sideEffects属性来实现的。</p>
<pre class=" language-javaScript"><code class="language-javaScript">&#123;
  "name": "tree-shaking",
  "sideEffects": false
&#125;</code></pre>
<p>如果所有代码都不包含副作用，我们就可以简单地将该属性标记为false，来告知webpack，它可以安全地删除未用到的export导出。</p>
<p>如果你的代码确实有一些副作用，那么可以改为提供一个数组:</p>
<pre class=" language-javaScript"><code class="language-javaScript">&#123;
  "name": "tree-shaking",
  "sideEffects": [
    "./src/common/polyfill.js"
  ]
&#125;</code></pre>
<h2 id="总结-1"><a href="#总结-1" class="headerlink" title="总结"></a>总结</h2><p>tree shaking不支持动态导入(如CommonJS的require()语法)，只支持纯静态的导入(ES6的import/export)</p>
<p>webpack中可以在项目package.json文件中，添加一个“sideEffects”属性,手动指定由副作用的脚本</p>
<h3 id="88-loader-会-plugins区别"><a href="#88-loader-会-plugins区别" class="headerlink" title="88.loader 会 plugins区别?"></a>88.loader 会 plugins区别?</h3><blockquote>
<p>两者都是为了扩展webpack的功能。<br>loader它只专注于转化文件（transform）这一个领域，完成压缩，打包，语言翻译; </p>
</blockquote>
<p>而plugin不仅只局限在打包，资源的加载上，还可以打包优化和压缩，重新定义环境变量等</p>
<p>loader运行在打包文件之前（loader为在模块加载时的预处理文件）；plugins在整个编译周期都起作用</p>
<p>一个loader的职责是单一的，只需要完成一种转换。</p>
<p>一个loader其实就是一个Node.js模块。当需要调用多个loader去转换一个文件时，每个loader会链式的顺序执行</p>
<p>在webpack运行的生命周期中会广播出许多事件，plugin会监听这些事件，在合适的时机通过webpack提供的API改变输出结果</p>
<h3 id="89-防抖和节流的区别及实现方式"><a href="#89-防抖和节流的区别及实现方式" class="headerlink" title="89.防抖和节流的区别及实现方式?"></a>89.防抖和节流的区别及实现方式?</h3><h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><ul>
<li>防抖(debounce)：<br>触发高频事件后n秒内函数只会执行一次，如果n秒内高频事件再次被触发，则重新计算时间。</li>
<li>节流(throttle)：<br>高频事件触发，但在n秒内只会执行一次，所以节流会稀释函数的执行频率。</li>
<li>目的：<br>节流（throttle）与 防抖（debounce）都是为了限制函数的执行频次，以优化函数触发频率过高导致的响应速度跟不上触发频率，出现延迟，假死或卡顿的现象。</li>
</ul>
<h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2><ul>
<li>window对象的resize、scroll事件</li>
<li>拖拽时的mousemove事件</li>
<li>文字输入、自动完成的keyup事件</li>
<li>射击游戏中的mousedown、keydown事件</li>
<li>实际上对于window的resize事件，实际需求大多为停止改变大小n毫秒后执行后续处理；而其他事件大多的需求是以一定的频率执行后续处理。</li>
</ul>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><h3 id="防抖-debounce"><a href="#防抖-debounce" class="headerlink" title="防抖(debounce)"></a>防抖(debounce)</h3><h3 id="实现方式："><a href="#实现方式：" class="headerlink" title="实现方式："></a>实现方式：</h3><p>每次触发事件时设置一个延迟调用方法，并且取消之前的延时调用方法</p>
<h3 id="缺点：-1"><a href="#缺点：-1" class="headerlink" title="缺点："></a>缺点：</h3><p>如果事件在规定的时间间隔内被不断的触发，则调用方法会被不断的延迟</p>
<pre class=" language-javaScript"><code class="language-javaScript">//防抖debounce代码：
function debounce(fn,delay) &#123;
    var timeout = null; // 创建一个标记用来存放定时器的返回值
    return function (e) &#123;
        // 每当用户输入的时候把前一个 setTimeout clear 掉
        clearTimeout(timeout); 
        // 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发，就不会执行 fn 函数
        timeout = setTimeout(() => &#123;
            fn.apply(this, arguments);
        &#125;, delay);
    &#125;;
&#125;
// 处理函数
function handle() &#123;
    console.log('防抖：', Math.random());
&#125;

//滚动事件
window.addEventListener('scroll', debounce(handle,500));</code></pre>
<h2 id="节流-throttle"><a href="#节流-throttle" class="headerlink" title="节流(throttle)"></a>节流(throttle)</h2><p>实现方式：每次触发事件时，如果当前有等待执行的延时函数，则直接return</p>
<pre class=" language-javaScript"><code class="language-javaScript">//节流throttle代码：
function throttle(fn,delay) &#123;
    let canRun = true; // 通过闭包保存一个标记
    return function () &#123;
         // 在函数开头判断标记是否为true，不为true则return
        if (!canRun) return;
         // 立即设置为false
        canRun = false;
        // 将外部传入的函数的执行放在setTimeout中
        setTimeout(() => &#123; 
        // 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
        // 当定时器没有执行的时候标记永远是false，在开头被return掉
            fn.apply(this, arguments);
            canRun = true;
        &#125;, delay);
    &#125;;
&#125;

function sayHi(e) &#123;
    console.log('节流：', e.target.innerWidth, e.target.innerHeight);
&#125;
window.addEventListener('resize', throttle(sayHi,500));</code></pre>
<h2 id="区别：-1"><a href="#区别：-1" class="headerlink" title="区别："></a>区别：</h2><p>函数节流不管事件触发有多频繁，都会保证在规定时间内一定会执行一次真正的事件处理函数，而函数防抖只是在最后一次事件后才触发一次函数。</p>
<p>比如在页面的无限加载场景下，我们需要用户在滚动页面时，每隔一段时间发一次 Ajax 请求，而不是在用户停下滚动页面操作时才去请求数据。</p>
<p>这样的场景，就适合用节流技术来实现。</p>
<h3 id="90-了解哪些新技术"><a href="#90-了解哪些新技术" class="headerlink" title="90.了解哪些新技术?"></a>90.了解哪些新技术?</h3><ul>
<li>Vue3</li>
<li>TypeScript</li>
<li>Webgl</li>
<li>VR</li>
<li>AR</li>
<li>Ai</li>
<li>python</li>
</ul>
<h3 id="91-控制台会报错么如果报错是什么类型的错误"><a href="#91-控制台会报错么如果报错是什么类型的错误" class="headerlink" title="91.控制台会报错么如果报错是什么类型的错误?"></a>91.控制台会报错么如果报错是什么类型的错误?</h3><pre class=" language-javaScript"><code class="language-javaScript">if(a == 1) &#123;
    console.log(a);
&#125;</code></pre>
<pre><code>a is not defined</code></pre>
<h3 id="92-以下代码"><a href="#92-以下代码" class="headerlink" title="92.以下代码"></a>92.以下代码</h3><pre class=" language-javaScript"><code class="language-javaScript">var a=?;
if(a==1&&a==2&&a==3)&#123;
     console.log('小样儿！');
 &#125;</code></pre>
<p>问：当a等于什么的时候，if条件成立，并打印？</p>
<h2 id="答案-1"><a href="#答案-1" class="headerlink" title="答案"></a>答案</h2><pre class=" language-javaScript"><code class="language-javaScript"> var a=&#123;
    num:1,
    toString:function()&#123;
       return a.num++;
    &#125;
  &#125;
 if(a==1&&a==2&&a==3)&#123;
     console.log("恭喜答对啦！");
 &#125;else&#123;
     console.log("还是错了小子！");
 &#125;</code></pre>
<h2 id="原理："><a href="#原理：" class="headerlink" title="原理："></a>原理：</h2><p>a==1&amp;&amp;a==2&amp;&amp;a==3，这是一个短路逻辑与运算符，表示左边条件为真时才会继续往右判断，否则立即整个判断像短路一样，所以 a 的第一个值必须是 a==1 为真才会继续向右判断 a==2，由此可以推断出 a 的值或者说是转换类型后的值是可以自增长的，JavaScript中当遇到不同类型的值进行比较时，会根据类型转换规则试图将它们转为同一个类型再比较。比如 Object 类型与 Number 类型进行比较时，Object 类型会转换为 Number 类型。转换为时会尝试调用 Object.valueOf 和 Object.toString 来获取对应的数字基本类型。</p>
<p>在上面代码中，逻辑转换先调用了valueOf方法，如果返回的还是对象，再接着调用toString()方法。每次比较都会先执行重写后的对象方法toString()，这个方法里先返回属性num的值再自增。执行a==1判断时，对象a调用toString()方法返回了属性num的值1，此时比较两个当然是相等的。与此类似，a==2和a==3一样成立。怎么样是不是很巧妙？</p>
<h3 id="93-说说原型和原型链？"><a href="#93-说说原型和原型链？" class="headerlink" title="93.说说原型和原型链？"></a>93.说说原型和原型链？</h3><h3 id="原型："><a href="#原型：" class="headerlink" title="原型："></a>原型：</h3><p>把所有的对象共用的属性全部放在堆内存的一个对象中（共用属性组成的对象），然后让每一个对象的<br>__proto__存储这个（共用属性组成的对象）的地址。而这个共用属性就是原型。原型出现的目的就是<br>为了减少不必要的内存消耗。</p>
<h3 id="原型链："><a href="#原型链：" class="headerlink" title="原型链："></a>原型链：</h3><p>而原型链就是对象通过__proto__向当前实例所属类的原型上查找属性或方法的机制，如果找到Object<br>的原型上还是没有找到想要的属性或者是方法则查找结束，最终会返回undefined，终点是null。</p>

                
            </div>
            <hr/>

            



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/pride-blog/tags/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/">
                                    <span class="chip bg-color">每天一个离职小技巧</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/pride-blog/libs/share/css/share.min.css">
<div id="article-share">

    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/pride-blog/2021/080441517.html">
                    <div class="card-image">
                        
                        
                        <img src="/pride-blog/medias/featureimages/23.jpg" class="responsive-img" alt="VueJS">
                        
                        <span class="card-title">VueJS</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2021-08-04
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/pride-blog/categories/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/" class="post-category">
                                    每天一个离职小技巧
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/pride-blog/tags/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/">
                        <span class="chip bg-color">每天一个离职小技巧</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/pride-blog/2021/080441514.html">
                    <div class="card-image">
                        
                        
                        <img src="/pride-blog/medias/featureimages/8.jpg" class="responsive-img" alt="CSS3">
                        
                        <span class="card-title">CSS3</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-08-04
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/pride-blog/categories/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/" class="post-category">
                                    每天一个离职小技巧
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/pride-blog/tags/%E6%AF%8F%E5%A4%A9%E4%B8%80%E4%B8%AA%E7%A6%BB%E8%81%8C%E5%B0%8F%E6%8A%80%E5%B7%A7/">
                        <span class="chip bg-color">每天一个离职小技巧</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/pride-blog/libs/codeBlock/codeShrink.js"></script>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/pride-blog/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2021-2023</span>
            
            <span id="year">2021</span>
            <a href="/pride-blog/about" target="_blank">zihao xiong</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">














</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/pride-blog/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/pride-blog/libs/materialize/materialize.min.js"></script>
    <script src="/pride-blog/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/pride-blog/libs/aos/aos.js"></script>
    <script src="/pride-blog/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/pride-blog/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/pride-blog/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/pride-blog/libs/others/clicklove.js" async="async"></script>
    
    

    

    

    <!--腾讯兔小巢-->
    
    
    <script type="text/javascript" color="0,0,255"
        pointColor="0,0,255" opacity='0.7'
        zIndex="-1" count="99"
        src="/pride-blog/libs/background/canvas-nest.js"></script>
    

    
    
    <script type="text/javascript" size="150" alpha='0.6'
        zIndex="-1" src="/pride-blog/libs/background/ribbon-refresh.min.js" async="async"></script>
    

    
    <script type="text/javascript" src="/pride-blog/libs/background/ribbon-dynamic.js" async="async"></script>
    

    
    <script src="/pride-blog/libs/instantpage/instantpage.js" type="module"></script><!-- hexo-inject:begin --><!-- hexo-inject:end -->
    

</body>
<script src="./../source/js/cursor.js"></script>

</html>
